I have an array of predicates. The array could contain n predicates.
How can I combine them by applying AND operation and arrive at a single predicate that I can use?
struct Car {
let name: String
let doors: Int
}
func f1() {
let p1 = #Predicate<Car> { $0.name == "aaa" }
let p2 = #Predicate<Car> { $0.doors == 4 }
let predicates = [p1, p2]
// how to combine predicates by applying AND?
}
Yep that looks like it should accomplish what you’re trying to do. If you want, you can even simplify it a little bit by using the Foundation-provided Predicate.true
func f1() {
let p1 = #Predicate<Car> { $0.name == "aaa" }
let p2 = #Predicate<Car> { $0.doors == 4 }
let predicates = [p1, p2] //could have more predicates
let predicate = predicates.reduce(.true) { result, current in
#Predicate<Car> {
result.evaluate($0) && current.evaluate($0)
}
}
}