Reputation: 9355
I am using a Dictionary for TableView. I also have a search bar for searching an item in the table.
The data is stored as following:
var namesDic = [String: [Name]]()
And I search through it as:
func updateSearchResults(for searchController: UISearchController) {
if searchController.searchBar.text! == "" {
filteredNames = namesDic
} else {
filteredNames.removeAll()
for persons in namesDic {
let person = persons.value.filter { $0.getName().contains(searchController.searchBar.text!)
}
for boy in person {
filteredNames[String(describing: boy.getName().characters.first!)] = [boy]
}
}
}
self.tableView.reloadData()
}
Problem: I only get one record now when I search for an item.
Is there a better way to implement above?
Upvotes: 1
Views: 1277
Reputation: 9355
More lines of code but it is working now. I stored values from dictionary in different variable and filtered those. The filtered values stored in the another variable and then iterate through.
func updateSearchResults(for searchController: UISearchController) {
if searchController.searchBar.text! == "" {
filteredNames = namesDic
} else {
filteredNames.removeAll()
var namesArray = [Name]()
for (_, value) in namesDic {
namesArray += value
}
let namesFilteredArray = namesArray.filter { $0.getName().lowercased().contains(searchController.searchBar.text!.lowercased())
}
for filteredName in namesFilteredArray {
if let letter = filteredName.getName().characters.first {
if filteredNames[String(letter)] != nil {
filteredNames[String(letter)]?.append(filteredName)
} else {
filteredNames[String(letter)] = [filteredName]
}
}
}
}
self.tableView.reloadData()
}
Upvotes: 1