问题
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