Ben Ben - 5 months ago 17
Swift Question

NSPredicate to filter an Array of Dictionaries (Swift)

I'm trying to learn the wonderful world of NSPredicate, but am failing on practical application. Any guidance is appreciated.

In particular, I want to use NSPredicate to filter an array of Dictionaries. For example, take the following array and filter it down to just those entries where "species" == "dog".

var arrayofDictionary:[[String:String]] = [

["name": "Ben", "species": "human"],
["name": "Harp", "species": "dog"],
["name": "Guinness", "species": "dog"]


Now I know how to filter the following way, but my understanding is this is the "lazy" way to do it and will not run as fast when doing large computations:

let filteredArray = arrayofDictionary.filter { $0["species"] == "dog" }.flatMap { $0 }

So I have been playing around with NSPredicate, and feel like the following may be a good starting place, but am not sure how to use it next. Also, perhaps this only works for an array and not dictionaries?

let speciesPredicate = NSPredicate(format: "species == %@", "dog")

Thanks for your help!

I was only able to find guidance on this in Objective-C here. Unfortunately I only am starting to pick up Swift.

This was a good tutorial on NSPredicate to start to get my head wrapped around it, but I couldn't figure out how to fully implement for the case mentioned above.


I agree with the comment by @luk2302, in that using the Swift Array filter method is nicer in general than filtering with an NSPredicate. If you're worried about performance across a large data set you should have your content in CoreData and use an NSPredicate as part of an NSFetchRequest with proper indexing setup in your data model.

Having said that, filtering by NSPredicate is not explicitly supporting with the Swift Array type, so you would have to cast to NSArray to use it. It would look something like this:

let filteredArray = (arrayofDictionary as NSArray).filteredArrayUsingPredicate(speciesPredicate)