Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create complicated NSCompoundPredicate in swift 3

I want to create a complicated NSCompoundPredicate in swift 3, however, I don't know how to do this.

Suppose I have 5 predicates (p1,p2,p3,p4,p5). I want to implement below conditions:

compound1 = (p1 AND p2 AND p3) // NSCompoundPredicate(type: .and, 
                              //subpredicates: predicates)
compound2 = (p4 AND p5) // NSCompoundPredicate(type: .and, 
                       //subpredicates: predicates)
compound3 = (compound1 OR compound2) // problem is here

fetchRequest.predicate = compound3

NSCompoundPredicate as it's second argument gets array of NSPredicates that it doesn't desire. What is the best solution?

like image 640
Amir Shabani Avatar asked Sep 24 '17 09:09

Amir Shabani


1 Answers

NSCompoundPredicate inherits from NSPredicate, therefore you can pass the compound predicates created in the first steps as subpredicate to another compound predicate:

let compound1 = NSCompoundPredicate(type: .and, subpredicates: [p1, p2, p3])
let compound2 = NSCompoundPredicate(type: .and, subpredicates: [p4, p5])
let compound3 = NSCompoundPredicate(type: .or, subpredicates: [compound1, compound2])

fetchRequest.predicate = compound3
like image 72
Martin R Avatar answered Oct 21 '22 10:10

Martin R