I am trying to search through a indexed dictionary to return a specific client based on the client's last name. Below are the data structures I am using. Each client object has a name property which is a String.
var clients = Client.loadAllClients() //Returns client array
var contacts = [String: [Client]]() //Indexed clients in a dictionary
var letters: [String] = []
var filteredClient = [Client]()
var shouldShowSearchResults = false
var searchController : UISearchController!
When I do my indexing, the contacts dictionary returns:
{A: [Client("Andrew")]}
Letters array returns:
[A]
I am using the UISearchController to display the filtered array of clients.
func updateSearchResults(for searchController: UISearchController) {
// how to filter the dictionary
self.tableView.reloadData()
}
However, I have no idea how to filter the dictionary to return the correct list of clients. I have tried to use
contacts.filter(isIncluded: ((key: String, value: [Client])) throws -> Bool((key: String, value: [Client])) throws -> Bool)
But I was very confused about the implementation. I am using Xcode 8.0 and Swift 3.0.
If anyone could point me in the right direction, that would be much appreciated. Please let me know if I need to clarify anything. Thank you in advance. The full code can be found at my Github
The main problem is that you are using a dictionary as data source array.
My suggestion is to use a custom struct as model
Then create your data source array
and the letter array as computed property
It's easy to sort the array by letter
Now you can search / filter this way (
text
is the text to be searched for)You can even keep the sections (letters) if you declare
filteredClient
also as[Contact]
and create temporaryContact
instances with the filtered items.Of course you need to change all table view data source / delegate methods to conform to the
Contact
array, but it's worth it. An array as data source is more efficient than a dictionary.