在 swift 3 中创建复杂的 NSCompoundPredicate

Create complicated NSCompoundPredicate in swift 3

我想在 swift 3 中创建一个复杂的 NSCompoundPredicate,但是,我不知道该怎么做。

假设我有 5 个谓词 (p1,p2,p3,p4,p5)。我想实现以下条件:

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 因为它的第二个参数得到它不想要的 NSPredicates 数组。什么是最好的解决方案?

NSCompoundPredicate 继承自 NSPredicate,因此你 可以传递在第一步中创建的复合谓词 作为另一个复合谓词的子谓词:

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