vblaga
vblaga

Reputation: 35

How to filter UISearchBar for multiple strings in Swift?

I have an array of struct's which each have a title and subtitle:

struct searchItem {
    var title: String
    var subtitle: String
}

let itemArray: [searchItem] = [
        searchItem(title: "Bob", subtitle: "Man"),
        searchItem(title: "Susan", subtitle: "Woman"),
        searchItem(title: "Joe", subtitle: "Man")
]

var filteredArray = [searchItem]()

Each searchItem's title and subtitle are used to create a tableViewCell in a tableViewController, with a UISearchBar at the top:

simulator image of tableView

I need to somehow filter the itemArray based on the search term, and each searchItem's title and subtitle, So either the search term "Man", or "Bob" will return the individual Bob.

How does one go about doing this? Thanks in advance!

Upvotes: 0

Views: 1783

Answers (2)

jorjj
jorjj

Reputation: 1599

Swift 3 version :

if let searchBarText = searchController.searchBar.text{
            let searchText = searchBarText.lowercaseString
            filteredArray = categoryArray.filter ({$0.title.lowercased().range(of: searchText.lowercased()) != nil})
            filteredArray += categoryArray.filter ({$0.sybtitle.lowercased().range(of: searchText.lowercased()) != nil})
            tableView.reloadData()
}

Upvotes: 1

emresancaktar
emresancaktar

Reputation: 1567

You can filter your array with filter method of swift array. When you use the filter it returns and another array of items depends on your searchText. So you should add searched items to your new filteredArray and reload your tableView.

if let searchBarText = searchController.searchBar.text{
            let searchText = searchBarText.lowercaseString
            filteredArray = self. itemArray.filter({$0.title.lowercaseString.rangeOfString(searchText) != nil})
            filteredArray += self.itemArray.filter({$0. subtitle.lowercaseString.rangeOfString(searchText) != nil})
            tableView.reloadData()
}

Upvotes: 2

Related Questions