skip to content

In a SwiftUI book list backed by SwiftData's @Query, why can a search field and genre picker in the same view not drive the query, and how do you fix it?

level: seniorimportance: must knowfreq 65%

answer

  1. filter fixed when the property is created
  2. property initializers cannot read self
  3. push state down into a child
  4. assign _books in init

basics

~20 s

A @Query's filter and sort are fixed when the property is created and cannot read the same view's @State. Keep the inputs in the parent, pass them to a child view, and build the query in its init with _books = Query(filter:sort:).

solid answer

~40 s

`@Query(filter:)` is evaluated once, when the view value is created, and a stored-property initializer cannot use instance members, so `#Predicate { $0.title.localizedStandardContains(searchText) }` with `searchText` as the same view's `@State` does not even compile. Reading the state inside that view's own `init` does not help either: it sees the initial value, and a state change re-runs `body`, not the init. The fix Apple's sample uses is to lift the inputs: the parent owns `searchText`, `genre` and the sort choice, and a child takes them as init parameters and assigns `_books = Query(filter: predicate, sort: descriptors)`. Each time the parent's body runs with new values, SwiftUI creates the child again with a new query. Guard empty text with `searchText.isEmpty ||`, because `localizedStandardContains("")` matches nothing.

code

swift · 40 lines
swift
import SwiftUI
import SwiftData

struct LibraryScreen: View {
    @State private var searchText = ""
    @State private var genre = "All"
    @State private var newestFirst = false

    var body: some View {
        NavigationStack {
            BookResults(searchText: searchText, genre: genre, newestFirst: newestFirst)
                .searchable(text: $searchText)
                .toolbar {
                    Picker("Genre", selection: $genre) {
                        ForEach(["All", "SF", "Fantasy"], id: \.self) { Text($0) }
                    }
                    Toggle("Newest first", isOn: $newestFirst)
                }
        }
    }
}

struct BookResults: View {
    @Query private var books: [Book]

    init(searchText: String, genre: String, newestFirst: Bool) {
        let filter = #Predicate<Book> { book in
            (searchText.isEmpty || book.title.localizedStandardContains(searchText))
                && (genre == "All" || book.genre == genre)
        }
        let sort = newestFirst
            ? [SortDescriptor(\Book.published, order: .reverse)]
            : [SortDescriptor(\Book.title)]
        _books = Query(filter: filter, sort: sort, animation: .default)
    }

    var body: some View {
        List(books) { Text($0.title) }
    }
}

go deeper

for a junior

Remember that a @Query cannot read the same view's @State, and that the fix moves the query into a child view.

for a middle

Explain why a property initializer cannot use self, why state changes do not re-run that view's init, and how _books = Query(...) replaces the property.

for a senior

Build the full child view: an empty-text guard, a type-consistent sort switch, a shared predicate function, and a plan for keystroke-heavy searches on a large store.

for a principal

Decide whether a team standardises on child-view queries or on iOS 27's ResultsObserver for filter-heavy screens, given the minimum iOS version it supports.

## Why the obvious version fails A library screen has a search field, a genre picker and a title-or-date sort toggle. The natural first draft puts all three as `@State` in the view and writes the filter into the macro: - `@Query(filter: #Predicate<Book> { $0.title.localizedStandardContains(searchText) })` does not compile. The macro's arguments are a property initializer, which runs before `self` exists, and the compiler says "instance member 'searchText' cannot be used on type". - Moving the query into that same view's `init` and reading `searchText` there compiles, but it reads the initial value. When the user types, SwiftUI re-runs this view's `body`; it does not call the view's `init` again because of its own state change, so the query keeps its first filter. The underlying rule: **a `@Query`'s filter, sort and descriptor are fixed when the property is created.** The `Query` struct has no settable filter. The only way to change them is to create a new `Query` value. ## The fix: rebuild the query in a child's initializer Split the screen in two: 1. **The parent** owns the inputs as `@State` (`searchText`, `genre`, `newestFirst`) and wires them to `.searchable`, a `Picker` and a `Toggle`. 2. **The child** declares `@Query private var books: [Book]` with no arguments and takes the inputs as plain `init` parameters. 3. In the child's `init`, build a `#Predicate` from the parameters and assign the backing property: `_books = Query(filter: predicate, sort: descriptors, animation: .default)`. Apple's earthquake sample describes exactly this: because the values are inputs to the view's initializer, SwiftUI re-evaluates the initializer to produce a new query whenever one changes, which updates the view. ## Writing the predicate and sort for it - **Capture plain values.** The predicate captures `searchText` and `genre` as `String`s. Captured values must be `Codable` and `Sendable` for the macro's output to type-check, which strings, numbers, dates and identifiers are. - **Handle "no filter" inside the predicate.** `(searchText.isEmpty || book.title.localizedStandardContains(searchText))` keeps every book while the field is empty; without the guard an empty search string matches nothing and the list goes blank. The same shape, `genre == "All" || book.genre == genre`, makes a picker option mean "any". - **Use `SortDescriptor` arrays for a switchable sort.** `\Book.title` and `\Book.published` are key paths with different value types, so a ternary between them cannot feed one `sort:` argument. Two `[SortDescriptor<Book>]` values share one type, so `newestFirst ? [SortDescriptor(\Book.published, order: .reverse)] : [SortDescriptor(\Book.title)]` works. Apple's sample instead switches and assigns a key-path query in each branch; both are fine. ## What happens on each keystroke 1. The user types, and `.searchable` writes the new text into the parent's `searchText` state. 2. SwiftUI re-runs the parent's `body`, which constructs `BookResults(searchText:genre:newestFirst:)` with the new value. 3. The child's `init` builds a fresh predicate capturing that text and assigns a new `Query` to `_books`. 4. When SwiftUI renders the child, the query fetches with the new filter, `books` holds the new matches, and the `animation:` argument animates rows in and out. Nothing in this loop is a manual fetch and nothing writes to the query's results: the child view is a function of its inputs plus the store. ## Things that go wrong in production | Symptom | Cause | Fix | |---|---|---| | List never changes as you type | state and `@Query` in the same view | move the query into a child that takes the text | | Empty list until you type | no `isEmpty` guard around `localizedStandardContains` | add `searchText.isEmpty \|\|` | | Search misses "Dune" for "dune" | `contains` compares case-sensitively in the store | use `localizedStandardContains` | | Typing feels slow on a big store | every keystroke builds a new query and fetch | debounce the text before passing it down | Two more habits help: - Keep the predicate in one static function on the model or view, as the sample does, so a list and a map showing the same data cannot disagree. - Pass a `FetchDescriptor` to `Query(_:animation:)` when the child also needs a `fetchLimit`. ## iOS 27: an observer you can re-filter The iOS 27 SDK adds **`ResultsObserver`**, an `Observable` class created with `filterBy:` and `sortBy:` (or a `FetchDescriptor`) and a model context. Its `filterBy` and `sortBy` properties are settable, and Apple's documentation says setting `filterBy` refetches immediately on the calling actor. That lets a filter that lives in an `@Observable` model change the results without rebuilding a view, but it is not a `@Query`: on earlier releases, and whenever the view's inputs are the natural home for the filter, the child-initializer pattern remains the answer.

  • Why does the child view not lose its query results every time the parent redraws?
    Recreating a view struct is normal and cheap in SwiftUI: the child keeps its identity because it stays at the same place in the hierarchy, and the new `Query` value only describes the fetch to run. Unchanged inputs describe the same fetch, so the same books show; a changed input describes a new one, and the list follows it.
  • When would you reach for iOS 27's ResultsObserver instead of a child-initializer @Query?
    When the filter already lives in an `@Observable` model, or code outside a view needs live results. You create the observer with a predicate, sort descriptors and a context, then set `filterBy` or `sortBy`; it refetches on the calling actor. On iOS 17 through 26, or when the filter is naturally a view input, the child initializer is simpler.

  • You can reference the view's @State inside the @Query macro's filter.
  • Reading @State in the same view's init keeps the query up to date.
  • @Query exposes a settable filter you can change from an onChange handler.
  • A title-or-date toggle works as a ternary between two key paths.
  • localizedStandardContains with an empty string matches every book.

Assumes the iOS 27 SDK: the child-initializer pattern works from iOS 17, while ResultsObserver with settable filterBy and sortBy is new in iOS 27.