Swift - Combining Predicates

对着背影说爱祢 提交于 2019-12-06 20:42:54

问题


Is there a way of combining predicates in Swift? For example:

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)

That gives me an error saying predicates cannot be arguments to other predicates. Is there another way to combine them?


回答1:


You'll need NSCompoundPredicate:

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



回答2:


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

You can use this also as per your different requirement

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


来源:https://stackoverflow.com/questions/31708540/swift-combining-predicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!