Hi I am trying to learn a bit more about NSPredicate- and its quite tough as the resources are still based on ObjC. I would like a swift based answer if possible
Basically I am trying to use NSPredicate to see if the arrays below contain a "9" the code number for Male users.
I thus want to filter the below people
array and only keep arrays that contain the number 9.
var malePerson1:[Int] = [1,4,5,6,11,9]
var malePerson2:[Int] = [3,5,6,7,12,9]
var femalePerson3:[Int] = [3,5,6,7,12,10]
var people = [malePerson1, malePerson2, femalePerson3]
I have got the solution working fine using a filter (see below)
//Solution working with Filter
// male gender search
var result = people.filter{$0.contains(9)}
print(result)
var resultFemale = people.filter{$0.contains(10)}
print(resultFemale)
but how Do I do something similar using predicates?
Below doesn't work - resultMale just returns a blank array when it should contain the two arrays: [maleperson1, maleperson2]
. I think the problem is that its checking if 9 is contained in the 'people' array instead of checking the contents of the contained arrays.
Any ideas how to do what I am doing using NSPredicate to filter the integers in the array?
let malePred = NSPredicate(format: "9 IN %@",people)
//9 is the code for Male user
var resultMale = (people as NSArray).filtered(using: malePred)
You can use ANY
to compare each nested array with NSPredicate
.
let malePred = NSPredicate(format: "ANY self == 9")