首页 > 解决方案 > 比较 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. 现在我想将IndexPathof发送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)
    }

}

但它可以更优化..请提出一些优化逻辑

标签: arraysswift

解决方案


这是查找要发送的索引的单行代码。

if !searchBarIsEmpty() {
    sendIndex = IndexPath(row: newsList.firstIndex(where: { $0.title == filteredList[indexPath.row].title }), section: 0)
}

注意: title假定为主键。与适当的主键进行比较。


推荐阅读