I have just started to learn swift and i am looking at the tableview and searchbar feature. Below i have my array which is a list of fruits:
var fruits: [[String]] = [["Apple", "Green"],["Pear", "Green"], ["Banana", "Yellow"], ["Orange", "Orange"]]
I have them in a table view with the name of the fruit as the title and the colour as a subtitle. I am trying to use the search bar to filter but i cant seem to get it right. I only want to search for the name of the fruit not the colour.
var filteredFruits = [String]()
var shouldShowSearchResults = false
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
filteredFruits.removeAll()
var i = 0
while i < fruits.count
{
var filteredFruits = fruits[i].filter ({ (fruit: String) -> Bool in
return fruit.lowercased().range(of: searchText.lowercased()) != nil
})
if searchText != ""
{
shouldShowSearchResults = true
if filteredItems.count > 0
{
filteredFruits.append(filteredItems[0])
filteredItems.removeAll()
}
}
else
{
shouldShowSearchResults = false
}
i += 1
}
self.tableView.reloadData()
}
I do get results returned but it mixes up the subtitles and the titles as well as not returning the correct results. Can anyone point me in the right direction?