Swift filter for multiple dictionary keys

I am creating a search bar for my application. I use the filter method to get the results. I want to search for a few keys.

Array of dictionaries:

 var people = [ ["First": "John", "Last": "Doe"], ["First": "Steve", "Last": "Jobs"], ["First": "Elon", "Last": "Musk"] ] 

I can only find β€œFirst” or β€œLast”, but not both, with this code:

 searchResults = people.filter{ var string = $0["Last"] // or "First" string = string?.lowercaseString return string!.rangeOfString(searchText.lowercaseString) != nil } 
+5
source share
3 answers

One approach would be to simply compare both fields with a search bar:

 var people = [ ["First": "JohnMusk", "Last": "Doe"], ["First": "Steve", "Last": "Jobs"], ["First": "Elon", "Last": "Musk"] ] var searchText = "Musk" var searchResults = people.filter{ var firstName = $0["First"]!.lowercaseString var lastName = $0["Last"]!.lowercaseString return firstName.rangeOfString(searchText.lowercaseString) != nil || lastName.rangeOfString(searchText.lowercaseString) != nil } 

This gives me this result:

 2015-11-18 18:19:47.691 MyPlayground[36558:7031733] ( { First = JohnMusk; Last = Doe; }, { First = Elon; Last = Musk; } ) 

I believe what you want.

+7
source

An alternative approach using NSPredicate used NSPredicate . NSPredicate has a very powerful syntax that can do pretty nice things for you.

 let firstNameQuery = "jo" let lastNameQuery = "mus" // [cd] means case/diacritic insensitive. %K is used to pass in key names since FIRST and LAST are reserved keywords in NSPredicate let predicate = NSPredicate(format: "%K CONTAINS[cd] %@ OR %K CONTAINS[cd] %@", "First", firstNameQuery, "Last", lastNameQuery) let sorted = people.filter({ return predicate.evaluateWithObject($0) }) // sorted would contain John Doe and Elon Musk entries 

In my example, I passed different search queries for the first and last name, but you could obviously go through the same query for both. Just demonstrates the power of this approach.

+4
source

The code below should work:

 var people = [ ["First": "John", "Last": "Doe"], ["First": "Steve", "Last": "Jobs"], ["First": "Elon", "Last": "Musk"] ] let searchResults = people.filter{ var found = false let searText = "Elon" for str in $0.values { found = str.lowercaseString.rangeOfString(searText.lowercaseString) != nil if found { break } } return found } 
+1
source

Source: https://habr.com/ru/post/1236278/


All Articles