Search code examples
swiftuisearchbaruisearchbardelegateuisearchbardisplaycontrol

How can I filter out contents via UISearchBar text?


I have a search with this code

extension PlacesVC : UISearchBarDelegate {

    func  searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        places = places.filter("name CONTAINS[cd] %@", searchBar.text)
        table.reloadData()
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchBar.text?.count == 0 {

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

        }
    }
}

I kept getting

Extra argument in call

Does anyone know what I missed and how to stop that ?


var places = [["lat": "40.718081110553925", "name": "59 Leonard St", "lon": "-74.00565161821724"], ["lat": "40.87124295389947", "name": "66 Lawrence Ave", "lon": "-74.0764477654279"], ["lat": "40.82326949018643", "name": "685 Fairview Ave", "lon": "-74.00056756991113"]]

Solution

  • You have an Array. You are trying to use filter but your arguments or more appropriate for NSPredicate. Use filter correctly.

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