arrays - 比较 2 个结果通过filteredList swift4的选定索引的对象
问题描述
我有 2 个相同自定义对象的列表,即新闻
class News: Object {
@objc dynamic var title: String?
@objc dynamic var date: Date?
@objc dynamic var contentUrl: String?
}
和 2 个列表是
var filteredList: Results<News>! = nil
var newsList: Results<News> {
get {
return realm.objects(News.self).sorted(byKeyPath: "date", ascending:
false)
}
}
我正在过滤列表,过滤后的数据存储在filteredList
. 现在我想将IndexPath
of发送newsList
给下一个 VC。当我在列表中搜索时,filteredList 附加到绝对正确的 tableView 中。当我从过滤列表中选择行时,它给出了过滤列表的索引。现在虽然用户选择了过滤列表的索引,它应该与对象进行比较newList
并返回那个 indexPath /index ofnewsList
我用我自己的方式做到了
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath:
IndexPath) {
searchController.dismiss(animated: true, completion: nil)
var sendIndex : IndexPath?
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
if !searchBarIsEmpty(){
for (index,news) in newsList.enumerated(){
if news.title == filteredList[indexPath.row].title{
sendIndex = IndexPath(row: index, section: 0)
}
}
}else{
sendIndex = indexPath
}
if let index = sendIndex{
let vc = NewsDetailsVC(collectionViewLayout: layout)
vc.tappedIndex = index
vc.title = "News Details"
vc.isSelectNews = true
self.navigationController?.pushViewController(vc, animated: true)
}
}
但它可以更优化..请提出一些优化逻辑
解决方案
这是查找要发送的索引的单行代码。
if !searchBarIsEmpty() {
sendIndex = IndexPath(row: newsList.firstIndex(where: { $0.title == filteredList[indexPath.row].title }), section: 0)
}
注意: title
假定为主键。与适当的主键进行比较。
推荐阅读
- javascript - 将 Hooks 函数导出为 react 组件的正确方法是什么?
- java - 有没有办法从哈希图中找到重复值,即 ArrayList?
- c++ - ShowWindow 仅在最后一次最小化时恢复窗口
- c - gprof 显示 0 计算时间
- angular - 如何在 ng-select 自定义标签上使用复制/粘贴
- javascript - Vue 和 firebase 未捕获类型错误:snapshot.forEach 不是函数
- c# - 如何将字节数组从 C# 传递到外部 DLL
- java - 使用 Java 计算 PI 近似值
- python - 聚合熊猫数据框中的相同连接行(时间序列组)
- javascript - 使用 vanilla js 获取 json 字符串中键的总和