快速搜索数组中的数据

问题描述

我的 tableview 顶部有一个搜索栏,它正在使用我的数据数组“title”进行搜索 我还想在标题旁边添加 Id,以便用户可以使用标题或帖子 ID 进行搜索 我试过了,但它只使用 id 搜索

  func searchBar(_ searchBar: UISearchBar,textDidChange searchText: String) {
    print("text did change")
    if searchText.count != 0 {
        self.isSearch = true // item["title"].string
        self.searchedData = self.data.filter { ($0["title"].string?.contains(searchText))! }
        self.searchedData = self.data.filter { ($0["id"].string?.contains(searchText))! }

        self.tableView.reloadData()
    } else {
        self.isSearch = false
        self.tableView.reloadData()
    }
}

}

是否也可以搜索标题

解决方法

问题在于您分配了第二个过滤器的结果并丢弃了前一个过滤器的结果。

您不应该强行打开表达式的结果。只是检查它是否属实。请注意,您可以避免将数据迭代两次 { $0["id"].string?.contains(searchText) == true || $0["title"].string?.contains(searchText) == true }