Combining predicates with AND

Hi,

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?
}

1 Like

Thanks to this post CompoundPredicate: A small library to combine Predicates - #2 by jmschonfeld

My attempt

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 truePredicate = #Predicate<Car> { _ in true }
    
    let predicate = predicates.reduce(truePredicate) { result, current in
        #Predicate<Car> {
            result.evaluate($0) && current.evaluate($0)
        }
    }
}

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)
        }
    }
}
2 Likes

@jmschonfeld Thanks a lot was searching for a easy / clean way to have a true predicate, thank you!!

1 Like