What can SwiftData's #Predicate express, and why does a filter on a computed Book property compile yet fail when the fetch runs?
answer
- the macro builds an expression tree
- three moments a predicate can fail
- only stored attributes reach the store
- compare identifiers, not models
basics
~20 s#Predicate turns a closure into an expression tree that SwiftData translates to a store query. Unsupported calls fail to compile, but a key path to a computed or @Transient property compiles and fails at fetch time: the store has no such column.
solid answer
~40 s`#Predicate` is a Foundation macro that rewrites a closure into `PredicateExpressions` values; SwiftData translates that tree into a query against the store. The macro accepts comparisons, `&&`, `||`, `!`, arithmetic, `??`, optional chaining and `if let`, collection `contains`, `contains(where:)`, `allSatisfy` and `filter`, `starts(with:)` and string helpers such as `localizedStandardContains`. Anything else fails at compile time: `lowercased()` gives "The lowercased() function is not supported in this predicate", and capturing a model instance fails because captured values must be `Codable` and `Sendable`, so compare `persistentModelID`. A key path is just a key path to the compiler, so `$0.displayTitle`, a computed property, compiles; but only stored attributes and relationships exist in the store, so the fetch fails. Some expressions the macro accepts but the store cannot run come back as a thrown `SwiftDataError`.
code
swift · 17 linesimport SwiftData
import Foundation
func unreadSciFi(by authorID: PersistentIdentifier, matching text: String) -> Predicate<Book> {
#Predicate<Book> { book in
book.genre == "SF"
&& !book.isRead
&& book.title.localizedStandardContains(text)
&& book.author?.persistentModelID == authorID
}
}
func prolificAuthors(minimum: Int) -> Predicate<Author> {
#Predicate<Author> { author in
author.books.count >= minimum && author.books.contains { !$0.isRead }
}
}go deeper
Know that #Predicate takes a closure over the model and that only some operations, such as comparisons and localizedStandardContains, are allowed.
Explain that the macro builds an expression tree, which calls it rejects, and why captured values must be plain Codable and Sendable values.
Name the three failure moments: compile error, thrown SwiftDataError, and a fatal error for non-persisted key paths, and show the persistentModelID and local-constant fixes.
Set a team habit of testing each new predicate shape against an in-memory store, since the compiler cannot prove a predicate will run.
## What the macro does `#Predicate<Book> { ... }` is a **Foundation** macro. It does not keep your closure: it rewrites each operation into a value from the `PredicateExpressions` namespace (an `Equal`, a `KeyPath`, a `Conjunction`, a captured `Value`) and wraps the tree in a `Predicate<Book>`. SwiftData then walks that tree and translates it into a query for its store. So a predicate can fail at three different moments, and a senior answer names all three. ## What it can express - **Comparisons and logic:** `==`, `!=`, `<`, `<=`, `>`, `>=`, `&&`, `||`, `!`, the ternary operator. - **Arithmetic:** `+`, `-`, `*`, `/`, `%`, unary minus. - **Optionals:** `??`, optional chaining (`book.author?.name == "Ursula"`), `if let` and `flatMap`. - **Collections:** `contains`, `contains(where:)`, `allSatisfy`, `filter`, `starts(with:)`, `min()`, `max()`, and key paths such as `count`. - **Strings:** `localizedStandardContains`, `caseInsensitiveCompare`, `localizedCompare`, and `contains` on a string. - **Relationships:** a to-one hop through an optional, and a to-many test such as `author.books.contains { !$0.isRead }` or `author.books.count >= minimum`. ## Failure 1: the build stops The macro only knows the operations above. Common compile errors: | You wrote | The compiler says | Write instead | |---|---|---| | `$0.title.lowercased().contains(text)` | "The lowercased() function is not supported in this predicate" | `$0.title.localizedStandardContains(text)` | | `... == .orderedSame` | "Member access without an explicit base is not supported in this predicate" | capture the value in a local `let` first | | `... == ComparisonResult.orderedSame` | "key path cannot refer to enum case" | the same local `let` | | `$0.author == someAuthor` | a type error building the predicate | `$0.author?.persistentModelID == authorID` | The last row matters most in practice. A captured value becomes a `PredicateExpressions.Value`, which is a standard predicate expression only when the value is `Codable` and `Sendable`. A model object is neither, so you capture its **`persistentModelID`** (a `PersistentIdentifier`) and compare identifiers. ## Failure 2: the store rejects it Some expressions the macro accepts cannot be translated into a store query. SwiftData reports these as a thrown **`SwiftDataError`**; the type declares `unsupportedPredicate`, `unsupportedKeyPath` and `unsupportedSortDescriptor` among its fetch errors. A regex match such as `$0.name.contains(/al/)` compiles and then throws `unsupportedPredicate` naming the `StringContainsRegex` operator. Inside a view, `@Query` surfaces that as `fetchError`; with `ModelContext.fetch(_:)` you catch it. ## Failure 3: the key path has no column To the compiler `\Book.displayTitle` is a valid key path whether `displayTitle` is stored or computed. The store, however, only has the model's **persisted attributes and relationships**. A predicate on a computed property, or on a property marked `@Transient`, passes the build and fails when the fetch runs. On the current SDK that failure is not a catchable error: the process stops with a fatal error such as "Couldn't find \Book.displayTitle on Book". The fix is to filter on stored data, or to store the derived value as its own attribute. ## Behaviour worth knowing 1. **String `contains` is case-sensitive** at the store: searching "dune" misses "Dune". `localizedStandardContains` ignores case and diacritics, so "cafe" finds "Café". 2. **An empty search string matches nothing** with `localizedStandardContains`; guard it with `searchText.isEmpty ||`. 3. **Captured values are copied when the predicate is built**, so a predicate built from a view's input reflects that input at creation. 4. **A `nil` hop never matches a value.** `book.author?.name == "Ursula"` is false for a book with no author, so a name filter quietly drops unowned books. ## Diagnosing a predicate in review 1. **Does it build?** If not, the macro's error names the unsupported call or the problem capture. 2. **Is every key path a stored attribute or relationship?** Computed and `@Transient` properties are the usual offenders, and the compiler cannot flag them. 3. **Does the store accept the operators?** Run the fetch once against a real container; a thrown `SwiftDataError` such as `unsupportedPredicate` names the operator. 4. **Are the match semantics right?** Check case and diacritics, the empty-input case and optional relationships that may be `nil`. Because the set of operations the macro accepts is wider than what every store can run, treat each new predicate shape as something to exercise once against a real store, for example in a test with an in-memory container, before it ships. ```swift let same = ComparisonResult.orderedSame let match = #Predicate<Book> { $0.title.caseInsensitiveCompare("DUNE") == same } ```
- How do you filter books by a given Author when you hold the Author model?Capture its identifier, `let authorID = author.persistentModelID`, and compare `book.author?.persistentModelID == authorID` inside the predicate. Capturing the model itself fails to build because a captured value must be `Codable` and `Sendable`, which a model object is not; the identifier is both.
- How do you match an enum case inside #Predicate?Bind the case to a local constant before the predicate and compare against that constant. Writing `.someCase` gives "Member access without an explicit base is not supported in this predicate", and writing the fully qualified case gives "key path cannot refer to enum case", because the macro treats a member reference as a key path.
- Why does a regex in #Predicate pass the build but fail in SwiftData?Foundation's predicate macro can represent a regex match, so the build succeeds, but SwiftData cannot translate that operator into a store query. The fetch throws a `SwiftDataError` with the `unsupportedPredicate` code, which `@Query` exposes as `fetchError`.
- Any Swift expression that compiles inside a closure works in #Predicate.
- A computed property in a predicate is evaluated in memory row by row.
- You compare relationships by capturing the model and using ==.
- String contains in a predicate already ignores case.
- If a predicate compiles, the fetch is guaranteed to run.