Search code examples
iosswiftrealmuisearchbaruisearchbardelegate

SearchBar Filter base on Object name - Swift 4


I have a search bar with these data format as a Realm object.

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

I'm trying to make the filter working

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

I kept getting

Cannot subscript a value of incorrect or ambiguous type

Any hints on what I did wrong ?


Solution

  • What also should work is if you are using NSPredicate

    let bPredicate: NSPredicate = NSPredicate(format: "SELF.name contains[cd] %@", searchText)
    places.filter(using: bPredicate)