基于对象名称的SearchBar过滤器-Swift 4

时间:2018-11-08 17:23:30

标签: ios swift realm uisearchbar uisearchbardelegate

我有一个搜索栏,这些数据格式作为Realm对象。

Optional(Results<Place> <0x7fb0d9e0bb10> (
[0] Place {
    name = Federal Street;
    country = United States;
    lat = 42.5447229;
    lon = -71.2809886;
},
...

我正在尝试使过滤器正常工作

enter image description here

//MARK: - Search bar methods
extension PlacesVC : UISearchBarDelegate {



    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        print("searchText \(searchText)")

        places = places.filter { ($0["name"] ?? "").range(of: searchBar.text ?? "", options: [ .caseInsensitive, .diacriticInsensitive ]) != nil }

        if searchBar.text?.count == 0 {

            load()

            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }

        }

        table.reloadData()
    }
}

我不断得到

  

无法下标错误类型或不明确类型的值

关于我做错什么的任何提示吗?

2 个答案:

答案 0 :(得分:2)

如果您正在使用NSPredicate

,也应该起作用
let bPredicate: NSPredicate = NSPredicate(format: "SELF.name contains[cd] %@", searchText)
places.filter(using: bPredicate)

答案 1 :(得分:0)

这就是我所做的

extension PlacesVC : UISearchBarDelegate {

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        places = places?.filter("name CONTAINS[c] %@", searchBar.text!).sorted(byKeyPath: "name", ascending: true)

        if searchBar.text?.count == 0 {

            load()

            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }

        }

        table.reloadData()
    }
}

它运行良好

enter image description here

希望这对以后像我这样的人有帮助。