The List Screen
Personal Catalogue: iOS (Swift & SwiftUI)
Course 1 ยท Chapter 4 ยท @Query, @Observable and Filter Chips
The store exists but nothing shows it. This chapter builds the app's home screen: a scrolling list of every item, newest first, with a row of chips to filter by type (Book, CD, DVD, Blu-ray), and a friendly
message when there is nothing to show. It also sets the pattern every later screen follows: SwiftData supplies the data with @Query, a small @Observable class holds the choices
the user makes, and the view draws both.
@Query with predicates and sorting. It found nothing on @Observable, ContentUnavailableView or the list/ForEach combination, so those are from my memory
of iOS 17 and later, and the code is the place to expect compile errors.
The Pattern Compared with Android
| Part | Android (Chapter 4) | iOS (this chapter) |
|---|---|---|
| Where the data comes from | Repository Flow, collected by the view model | @Query in the view; SwiftUI refreshes it when the store changes |
| Where the user's choices live | MutableStateFlow in the ViewModel | Properties of an @Observable class held in @State |
| How a screen is split | Stateful composable and stateless composable | One view, with the logic that can be tested moved into the view model |
| The scrolling list | LazyColumn | List with ForEach |
| Filter chips | FilterChip in a LazyRow | Buttons styled as chips, in a horizontal ScrollView |
| Empty state | A Box with a message | ContentUnavailableView |
The split is much lighter on iOS. The Android view model had to combine three flows and turn them into state; here SwiftUI does the "collect and redraw" part for you, so the view model shrinks to the user's choices plus any logic worth testing.
Step 1: The View Model
@Observable (from the Observation framework, iOS 17 and later) makes a class's properties trackable: any SwiftUI view that reads one is redrawn when it changes, with no @Published
or ObservableObject needed. For now the model holds one choice, the selected type, plus a function that applies it. Create ListViewModel.swift:
Be honest about why this exists: for a single optional property, a plain @State private var selectedTypeName: String? in the view would do. It is a class here for three reasons: it mirrors the
Android course, Chapter 8 adds the search text and the tag filter to it, and filtered(_:) is plain Swift that Chapter 10 can test without any UI.
Step 2: The Query
@Query is a property wrapper that fetches models and keeps the result current. Sorting is given as a key path and an order:
The first line is "every item, newest first". Add or delete an item anywhere in the app and items changes by itself: that is the equivalent of Room's Flow from the Android course.
Why filter in memory rather than in the query? A query can take a #Predicate, and the sources I found show the usual way to make it depend on a choice: build the
Query in the view's own init, passing the choice in. But that pattern has costs: the @Query has to be assigned in a custom initialiser, an Apple forum reply says SwiftData
cannot tell whether the predicate changed and so re-fetches whenever that init runs, and one of the search results is a thread about a runtime crash with a predicate. Filtering a handful of types
out of an array in Swift is simpler and safe, exactly as it was on Android in this chapter. Chapter 8, where search and tag filters need the database, uses the dynamic-query pattern properly.
Step 3: The Screen
Create ListView.swift. The view owns the model with @State; that matters, and Exercise 3 asks you to explain why.
Points worth knowing. $model.selectedTypeName is a binding to the property: the chips read it and write it, and writing redraws the view. ForEach(shownItems) needs no explicit id,
because every @Model class is identifiable (the assumption flagged in Chapter 3). List only builds rows as they scroll into view, so it suits a list of unknown length, as
LazyColumn did on Android. The two empty messages come from comparing items (everything) with shownItems (after the filter): "Your catalogue is empty" only when there really
is nothing, "Nothing of this type yet" when the filter hides everything. NavigationStack is here only to provide the title bar and toolbar; Chapter 5 gives it destinations.
Step 4: The Chips and the Rows
SwiftUI's built-in controls do not include a chip, so build one from a Button with a capsule background. TypeFilterRow puts an "All" chip and one per type in a horizontal
ScrollView:
The colours are system and semantic ones (.primary, .accentColor, secondarySystemBackground), never fixed values, so they adapt to light and dark appearance without any
extra work: Chapter 9 relies on that. The isSelected accessibility trait lets VoiceOver say which chip is chosen. Each row is a small view of its own:
typeName and sortedTags are the helper properties from Chapter 2, which is exactly what they were for. item.releaseYear.map(String.init) turns an optional
year into an optional string, so a missing year simply disappears from the byline.
Step 5: Wiring and Previews
Make RootView show the new screen instead of the temporary one, and delete the temporary ContentView from Chapter 3 (change ContentView() in RootView to
ListView()). Add an empty-store container to PreviewData so the empty state can be previewed too, and use it:
Both containers are created once and shared, as Chapter 3 explained. Run the app: you should see "Your catalogue is empty". Tap "+" a few times and sample rows appear immediately, newest first, with no refresh
code: @Query noticed the store change. Tap a type chip that no sample item uses (only the first type, Book, is used) to see the second empty message.
Flows into one state object, and a split between a stateful and a stateless composable. On
iOS the "collect and redraw" machinery is built in, so the same screen is one view plus a tiny model. The cost is that you have less control: you cannot easily see, or change, exactly when SwiftData re-fetches.
Both versions end with the same behaviour: items appear and disappear as the data changes, and the type filter and the two empty states work the same way.
Challenges
Add ListViewModel, ListView, TypeFilterRow, FilterChip and ItemRow, update RootView and the previews, and run it. Tap
"+" three times, tap the CD chip, then All. Write down what you see for each of the two empty messages and how you triggered each.
Change the navigation title to show the number of items currently listed, for example "My Catalogue (3)". Decide where the number should be computed: in the view, or as a property of
ListViewModel.
The model is stored with @State private var model = ListViewModel(). Explain what would go wrong with private let model = ListViewModel() instead, and why the chip
selection survives the user rotating the phone. Then say whether the selection survives the app being quit and reopened, and name a property wrapper that would make it do so.
Chapter 4 Quick Reference
@Query(sort: \Item.createdAt, order: .reverse) private var items: [Item]fetches and keeps itself current@Observable final class(iOS 17+) holds user choices; own it with@State private var model = ...; bind with$model.property- Filter in memory for a simple choice; for database-side filtering build the
Queryin the view'sinit(Chapter 8) List { ForEach(items) { ... } }builds rows lazily;@Modelclasses are identifiable- Chip: a
Buttonwith.buttonStyle(.plain)and aCapsulebackground, using semantic colours and the.isSelectedaccessibility trait ContentUnavailableView("Title", systemImage:, description:)for empty states; two of them: no items at all, and no items of the chosen type- Previews:
#Preview("name") { ListView().modelContainer(PreviewData.container) }with shared containers
@Query depend on a value is to assign it in the view's init (_items = Query(filter:sort:)),
from a Stack Overflow answer and Hacking with Swift material; that a search tutorial relies on the view being re-initialised when the search text changes; and, from an Apple forum reply, that SwiftData assumes a
re-fetch each time that init runs because it cannot tell whether the predicate changed. The search also surfaced Apple's page "Filtering and sorting persistent data" and a thread about a runtime
crash with the predicate macro, neither of which I read in detail.Not checked, from general knowledge:
@Query(sort:order:) with a key path and .reverse; @Observable and @State ownership on iOS 17 and later;
ContentUnavailableView and its initialiser; Button(_:systemImage:); ToolbarItem(placement: .primaryAction); .foregroundStyle(.tint);
.accessibilityAddTraits(.isSelected); that @Model classes need no explicit id in ForEach; and all code, none of which was compiled. I did not
consult Apple's reference pages for any of these APIs.
NavigationStack and navigationDestination, the detail layout, and deleting an
item after a confirmation.