SearchBar Filter base on Object name - Swift 4

2.1k views Asked by At

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 ?

2

There are 2 answers

2
Retterdesdialogs On BEST ANSWER

What also should work is if you are using NSPredicate

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

This is what I did

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

and it is working perfectly

enter image description here

Hope this will help someone like me in the future.