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

SearchBar Filter base on Object name - Swift 4

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

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

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

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



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

        print("searchText \(searchText)")

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

        if searchBar.text?.count == 0 {

            load()

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

        }

        table.reloadData()
    }
}

我一直在

Cannot subscript a value of incorrect or ambiguous type

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

如果您使用的是 NSPredicate

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

这就是我所做的

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()
    }
}

它运行良好

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