With SwiftData's @Query, how do you show a library's books in a SwiftUI List sorted by title, and when does that list update?
answer
- a macro on a view property
- sort key path or descriptors
- insert through the context, not the array
- kept in sync with the store
basics
~20 sDeclare @Query(sort: \Book.title) var books: [Book] in the view and hand books to List. The query fetches from the environment's model context and stays in sync, so inserts, deletes and edits redraw the list without a refetch.
solid answer
~40 s`@Query` is a SwiftData macro you attach to a stored property of a SwiftUI view. It fetches every model of the element type from the model context in the view's environment and, in Apple's words, keeps those models in sync with the underlying data. `@Query(sort: \Book.title) private var books: [Book]` gives an array ordered by title; add `order: .reverse`, pass an array of `SortDescriptor`s to sort on several keys, add `filter:` with a `#Predicate`, or `animation:` so rows animate in and out. The array is read-only: you add a book by calling `insert` on the model context and the query picks it up. The view needs a model container installed somewhere above it, and the sort key must be `Comparable`, so a `Bool` property cannot be a key-path sort.
code
swift · 21 linesimport SwiftUI
import SwiftData
struct LibraryView: View {
@Environment(\.modelContext) private var context
@Query(sort: \Book.title, animation: .default) private var books: [Book]
var body: some View {
NavigationStack {
List(books) { book in
Text(book.title)
}
.navigationTitle("Library (\(books.count))")
.toolbar {
Button("Add") {
context.insert(Book(title: "Dune", genre: "SF", published: .now))
}
}
}
}
}go deeper
Write the declaration from memory: @Query with sort, an array type, and the List that reads it. Know that new models go in through the context.
Explain the key-path versus SortDescriptor forms, the Comparable requirement, the default localizedStandard string comparator and why the array is read-only.
Show how you would surface fetchError, when an animation belongs on the query, and why copying query results into separate state causes stale screens.
Be ready to say when a screen outgrows a plain @Query, for example needing limits, sections or user-driven filters, and which of those the iOS 27 SDK now covers.
## What @Query is **`@Query`** is a macro from SwiftData's SwiftUI layer. Attached to a stored property of a SwiftUI view, it expands into a backing property named with an underscore prefix (`_books`) of type `Query<Book, [Book]>`, which is a SwiftUI `DynamicProperty`. When SwiftUI renders the view, that property fetches models of the element type from the **model context** found in the view's environment and exposes them as the property's value. Apple's documentation describes it as a type that fetches models using the criteria you give it and manages them so they *remain in sync with the underlying data*. Three consequences follow: - **There is no load call.** The first render fetches; later changes to matching models redraw the view. - **The value is read-only.** `wrappedValue` has only a getter, so `books.append(...)` does not compile. You change data through the context (`insert`, `delete`, or by editing a model's properties) and the query reflects it. - **It is main-actor isolated.** `Query` is declared `@MainActor`, like the view that owns it. Installing the model container and reading the context from the environment are the view-wiring side of SwiftData and are covered with SwiftData's SwiftUI integration; `@Query` only assumes they are there. ## Sorting The macro offers two ways to describe order: | Form | Example | Use it when | |---|---|---| | Key path plus `order:` | `@Query(sort: \Book.title, order: .reverse)` | one sort key | | Array of `SortDescriptor` | `@Query(sort: [SortDescriptor(\Book.genre), SortDescriptor(\Book.title)])` | several keys, applied in array order | | A `FetchDescriptor` | `@Query(descriptor)` | you also need `fetchLimit` or other descriptor options | Points interviewers probe: 1. The key-path form requires a **`Comparable`** value. `@Query(sort: \Book.isRead)` fails with "requires that 'Bool' conform to 'Comparable'". 2. Optional key paths are accepted too: there are overloads for `KeyPath<Element, Value?>`. 3. A `SortDescriptor` built on a `String` key path defaults to the **`.localizedStandard`** comparator, so "Book 2" sorts before "Book 10"; pass `comparator: .lexical` for plain ordering. ## Filtering and animation `filter:` takes a `Predicate<Book>` built with `#Predicate`, for example `#Predicate<Book> { !$0.isRead }`. `animation:` (or `transaction:`) tells SwiftUI how to animate the change when a fetch result differs from the previous one, so a newly inserted book slides into place rather than popping in. ```swift @Query(filter: #Predicate<Book> { !$0.isRead }, sort: \Book.published, order: .reverse) private var unread: [Book] ``` The filter and sort you write here are fixed for the life of that property; changing them from user input is done by rebuilding the query in a view initializer, a separate topic. ## When the list updates - **Inserts and deletes** on the context show up in the array without any manual refetch. - **Edits** to a fetched model's properties redraw the rows that read them. - **Fetch errors** do not empty the list: `_books.fetchError` holds the latest error, and `wrappedValue` keeps the results of the last successful fetch until a new fetch succeeds. ## Grouping into sections (iOS 27) From iOS 27 the macro has `sectionBy:` overloads that take a `String` or `String?` key path and produce **`SectionedResults<Book, String>`**. Iterating it yields `ResultsSection` values, each with a `title` and its own models; a `nil` key lands in the empty-string section. ```swift @Query(sort: \Book.title, sectionBy: \Book.genre) private var shelves: SectionedResults<Book, String> ``` Before iOS 27 you grouped the flat array yourself, for example with `Dictionary(grouping:by:)` in the view. ## @Query or a fetch in code `@Query` belongs to a view that displays data. Code that runs outside a view, such as an import routine, a widget timeline or a unit test, builds a `FetchDescriptor` and calls `fetch(_:)` on a model context instead. Both describe a fetch the same way, with a predicate, sort descriptors and optional limits, which is why `@Query` also accepts a `FetchDescriptor`: - **`@Query`** lives in a SwiftUI view, fetches when the view renders, follows the store and runs on the main actor. - **`ModelContext.fetch(_:)`** is one-shot: it returns an array at the moment you call it, throws on failure, and runs wherever its context lives. A useful review rule: a view that calls `fetch(_:)` in `onAppear` and keeps the result in `@State` has rebuilt `@Query` badly, because that copy will not follow later inserts. ## Common mistakes - Treating the array as storage: appending to it, or copying it into `@State` and then editing the copy. - Calling `fetch(_:)` on the context after every insert "to refresh" the list; the query already follows the store, and a manual fetch result does not feed `@Query`. - Putting `@Query` in an `@Observable` view model: it is a SwiftUI dynamic property and works in views. - Forgetting the container: with no model container above the view there is no context to fetch from.
- How do you find out that a @Query fetch failed?Read the backing property's `fetchError`, for example `_books.fetchError`, inside `body`. It is `nil` unless the most recent fetch failed. The documentation adds that `wrappedValue` keeps the results of the last successful fetch while an error is present, so an empty list and a failed fetch are different states you can tell apart.
- Why does a SwiftData title sort put "Book 2" before "Book 10"?A `SortDescriptor` on a `String` key path uses the `.localizedStandard` comparator unless you pass another one. That comparator is locale-aware and compares a run of digits inside the string by its numeric value. Pass `comparator: .lexical` to `SortDescriptor` when you need plain character-by-character order.
- How do you show only the five newest books with @Query?Build a `FetchDescriptor<Book>` sorted by date in reverse, set its `fetchLimit` to 5, and pass it to `@Query(descriptor)`. The macro's filter-and-sort overloads have no limit parameter, so a limit always travels inside a fetch descriptor; a static computed property on the view is a tidy place to build it.
- You add a new book by appending it to the @Query array.
- @Query fetches once, so you must refetch after every insert.
- @Query works the same inside an @Observable view model as in a view.
- Any stored property, including a Bool, can be a key-path sort.
- A failed @Query fetch silently empties the list.
Assumes the iOS 27 SDK: @Query and its sort and filter forms date from iOS 17, while sectionBy and SectionedResults are new in iOS 27.