斯威夫特 - 结合谓词

时间:2015-07-29 18:36:51

标签: ios swift nspredicate

有没有办法在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)

这给了我一个错误,说谓词不能成为其他谓词的参数。还有另一种方法可以将它们结合起来吗?

2 个答案:

答案 0 :(得分:20)

您需要NSCompoundPredicate

let predicate1 = NSPredicate("self.label = 'foo'"))
let predicate2 = NSPredicate("self.label = 'bar'"))
let compound = NSCompoundPredicate.andPredicateWithSubpredicates([predicate1, predicate2])

答案 1 :(得分:5)

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])