【问题标题】:Search for data in array in swift快速搜索数组中的数据
【发布时间】:2021-02-07 15:59:48
【问题描述】:

我的表格视图顶部有一个搜索栏,它正在使用我的数据数组“标题”进行搜索 我还想在标题旁边添加 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()
    }
}

}

是否也可以搜索标题?

【问题讨论】:

    标签: ios arrays swift xcode uisearchbar


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-18
      • 1970-01-01
      相关资源
      最近更新 更多