Hello Swift Community,
Lately, I've been increasingly frustrated with the limitations of Predicates in Swift, especially when it comes to combining them, unlike NSPredicate. The documentation on this topic has been rather vague, leading to numerous failed attempts and a descent into madness, which I've documented in my Stack Overflow post and in Fatbobman's article here.
However, I come bearing good news! I'm thrilled to announce the release of "CompoundPredicate"
This small library addresses the issue of combining predicates without the need for a custom PredicateExpression (which is not supported in SwiftData) and without the hassle of manually constructing expressions.
You can find the source code and documentation on GitHub.
Using it to combine predicates is easy:
import CompoundPredicate
let notTooShort = #Predicate<Book> {
$0.pages > 50
}
let notTooLong = #Predicate<Book> {
$0.pages <= 350
}
let lengthFilter = [notTooShort, notTooShort].conjunction()
// Match Books that are just the right length
let titleFilter = #Predicate<Book> {
$0.title.contains("Swift")
}
// Match Books that contain "Swift" in the title or
// are just the right length
let filter = [lengthFilter, titleFilter].disjunction()