0

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)
2
  • 1
    This is not a duplicate - the potential solutions are in objective C( and very old syntax) These solutions don't work on Swift Commented May 31, 2017 at 10:10
  • The predicate syntax is the same for Swift and Objective-C. For your case it is "ANY self == value", regardless which language you use. Commented May 31, 2017 at 11:07

1 Answer 1

2

You can use ANY to compare each nested array with NSPredicate.

let malePred = NSPredicate(format: "ANY self == 9")
Sign up to request clarification or add additional context in comments.

4 Comments

Awesome @Nirav . - out of interest would it work if i want to filter on 9, 10 eg? ANY self == [9, 10]"
@MobileBloke Welcome mate :), You can use IN for that let malePred = NSPredicate(format: "ANY self IN %@",[9, 10])
Oops! - Done ! Thanks for the help. Where do you learn all this about predicates? The Documentation seems quite weak.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.