Dynamic Compound Predicates

This is relating to the question I have for the App Intents framework (see my question).

I know that SwiftData started to support compound predicates with macOS 14.4/iOS 17.4 or later. But from what I understand they are not dynamic and are validated at compile time.

Is there a way to update/construct predicates while the app is running? For example to create a search tab that allows searching and filtering for my items in the app.

Answered by Frameworks Engineer in 891843022

Yes, you can dynamically construct a conjunction or disjunction of subpredicates starting in the 2027 releases. Here is an example of a conjunction:

let predicates = [#Predicate<Int> { $0 > 2 }, #Predicate<Int> { $0 <= 9 }, #Predicate<Int> { $0 != 5 }, #Predicate<Int> { $0 % 2 != 0 }]
let conjunction = Predicate(all: predicates)

For a disjunction, use Predicate(any:). Read more in the API proposal on Swift Forums.

Accepted Answer

Yes, you can dynamically construct a conjunction or disjunction of subpredicates starting in the 2027 releases. Here is an example of a conjunction:

let predicates = [#Predicate<Int> { $0 > 2 }, #Predicate<Int> { $0 <= 9 }, #Predicate<Int> { $0 != 5 }, #Predicate<Int> { $0 % 2 != 0 }]
let conjunction = Predicate(all: predicates)

For a disjunction, use Predicate(any:). Read more in the API proposal on Swift Forums.

Dynamic Compound Predicates
 
 
Q