Swift - 组合谓词

Swift - Combining Predicates

在Swift中是否有组合谓词的方法?例如:

let predicate1 = NSPredicate("self.label = 'foo'"))
let predicate2 = NSPredicate("self.label = 'bar'"))
let combinedPredicate = NSPredicate("self.staticTexts.elementMatchingPredicate(%@).exists AND
  self.staticTexts.elementMatchingPredicate(%@).exists", predicate1, predicate2)

这给了我一个错误,说谓词不能作为其他谓词的参数。还有其他方法可以组合它们吗?

你需要 NSCompoundPredicate:

let predicate1 = NSPredicate(format: "self.label = 'foo'", argumentArray: [])
let predicate2 = NSPredicate(format: "self.label = 'bar'", argumentArray: [])
let compound = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1, predicate2])
let predicate1:NSPredicate = NSPredicate("self.label = 'foo'")
let predicate2:NSPredicate = NSPredicate("self.label = 'bar'")
let compound:NSCompoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate1,predicate2])
self.filteredArray = self.array.filteredArrayUsingPredicate(compound)
self.table.reloadData()

您也可以根据您的不同要求使用它

let compound:NSCompoundPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [predicate1,predicate2])