Tarvo Mäesepp
Tarvo Mäesepp

Reputation: 4533

Searching trough NSDictionary using search bar

I would like to know how I am able to filter NSDictionary using searchBar?

I declared 2 variables var usersArray = [NSDictionary?]() and var filteredUsers = [NSDictionary?]()

Now I am trying to filter them like this:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        self.filteredUsers = self.usersArray.filter{ user in
        let username = user!["username"] as? String
        return(username?.lowercased().contains(searchText.lowercased()))!
    }
        if searchText != ""{
            shouldShowSearchResults = true
            followUsersTableView.reloadData()
        }else{
            shouldShowSearchResults = false
            followUsersTableView.reloadData()
        }

    }

And I do the updateSearchResults:

filteredUsers.removeAll(keepingCapacity: false)

        let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
        let array = (usersArray as NSDictionary).filtered(using: searchPredicate)
        filteredUsers = array as! [String]

        self.followUsersTableView.reloadData()

But for some reason it is not filtering it.

How should I do it?

Upvotes: 0

Views: 753

Answers (1)

Ace Green
Ace Green

Reputation: 391

Whipped this out in playground, works fine

var usersArray = ["Adam", "Eve", "Ace", "Michael"]
var filteredUsers: [String]
var searchText: String = "a"

filteredUsers = usersArray.filter { $0.lowercased().contains(searchText.lowercased()) }
print(filteredUsers)

PS I would change your if statment to check if !filteredUsers.isEmpty rather than searchText. because you really only want to reload if that array has something to show, regardless if the searchText is nil or not

enter image description here

Upvotes: 1

Related Questions