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.

What was run, and what was not
Nothing in this chapter was compiled or run (no Mac or Xcode here). My search found tutorials, forum posts and one Apple documentation page, "Filtering and sorting persistent data", on @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

PartAndroid (Chapter 4)iOS (this chapter)
Where the data comes fromRepository Flow, collected by the view model@Query in the view; SwiftUI refreshes it when the store changes
Where the user's choices liveMutableStateFlow in the ViewModelProperties of an @Observable class held in @State
How a screen is splitStateful composable and stateless composableOne view, with the logic that can be tested moved into the view model
The scrolling listLazyColumnList with ForEach
Filter chipsFilterChip in a LazyRowButtons styled as chips, in a horizontal ScrollView
Empty stateA Box with a messageContentUnavailableView

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:

import Foundation import Observation @Observable final class ListViewModel { /// The name of the selected item type; nil means "All". var selectedTypeName: String? /// Applies the type filter to an already-sorted list. func filtered(_ items: [Item]) -> [Item] { guard let name = selectedTypeName else { return items } return items.filter { $0.type?.name == name } } }

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:

@Query(sort: \Item.createdAt, order: .reverse) private var items: [Item] @Query(sort: \ItemType.sortOrder) private var types: [ItemType]

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.

import SwiftUI import SwiftData struct ListView: View { @Environment(\.modelContext) private var context @Query(sort: \Item.createdAt, order: .reverse) private var items: [Item] @Query(sort: \ItemType.sortOrder) private var types: [ItemType] @State private var model = ListViewModel() private var shownItems: [Item] { model.filtered(items) } var body: some View { NavigationStack { VStack(spacing: 0) { TypeFilterRow(types: types, selected: $model.selectedTypeName) if items.isEmpty { ContentUnavailableView( "Your catalogue is empty", systemImage: "books.vertical", description: Text("Tap + to add your first item.") ) } else if shownItems.isEmpty { ContentUnavailableView( "Nothing of this type yet", systemImage: "line.3.horizontal.decrease.circle", description: Text("Choose All to see everything.") ) } else { List { ForEach(shownItems) { item in ItemRow(item: item) } } } } .navigationTitle("My Catalogue") .toolbar { ToolbarItem(placement: .primaryAction) { Button("Add", systemImage: "plus") { addSampleItem() } // TEMPORARY } } } } // TEMPORARY: lets you see rows before the form exists (Chapter 6 removes this). private func addSampleItem() { guard let type = types.first else { return } let item = Item(title: "Sample item", creator: "Sample creator", type: type) try? CatalogueRepository(context: context).save(item, tagNames: []) } }

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:

import SwiftUI struct TypeFilterRow: View { let types: [ItemType] @Binding var selected: String? var body: some View { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 8) { FilterChip(title: "All", isSelected: selected == nil) { selected = nil } ForEach(types) { type in FilterChip(title: type.name, isSelected: selected == type.name) { selected = type.name } } } .padding(.horizontal) .padding(.vertical, 8) } } } struct FilterChip: View { let title: String let isSelected: Bool let action: () -> Void var body: some View { Button(action: action) { Text(title) .font(.subheadline) .padding(.horizontal, 14) .padding(.vertical, 7) .foregroundStyle(isSelected ? Color.white : Color.primary) .background(isSelected ? Color.accentColor : Color(.secondarySystemBackground), in: Capsule()) } .buttonStyle(.plain) .accessibilityAddTraits(isSelected ? .isSelected : []) } }

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:

import SwiftUI struct ItemRow: View { let item: Item private var byline: String { [item.creator.isEmpty ? nil : item.creator, item.releaseYear.map(String.init)] .compactMap { $0 } .joined(separator: " ยท ") } var body: some View { VStack(alignment: .leading, spacing: 4) { Text(item.title) .font(.headline) .lineLimit(2) if !byline.isEmpty { Text(byline) .font(.subheadline) .foregroundStyle(.secondary) } Text(([item.typeName] + item.sortedTags.map(\.name)).joined(separator: " ยท ")) .font(.caption) .foregroundStyle(.tint) } .padding(.vertical, 2) } }

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:

// In PreviewData: static let emptyContainer: ModelContainer = { let container = try! Persistence.makeContainer(inMemory: true) try! CatalogueRepository(context: container.mainContext).ensureSeeded() return container }() // At the bottom of ListView.swift: #Preview("With sample data") { ListView().modelContainer(PreviewData.container) } #Preview("Empty catalogue") { ListView().modelContainer(PreviewData.emptyContainer) }

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.

Compare with the Android course
Personal Catalogue: Android (Kotlin & Compose) Chapter 4 needed a view model that combined three 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

Exercise 1

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.

๐Ÿ“„ View solution
Exercise 2

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.

๐Ÿ“„ View solution
Exercise 3

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.

๐Ÿ“„ View solution

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 Query in the view's init (Chapter 8)
  • List { ForEach(items) { ... } } builds rows lazily; @Model classes are identifiable
  • Chip: a Button with .buttonStyle(.plain) and a Capsule background, using semantic colours and the .isSelected accessibility 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
Not Yet Verified
Checked (one web search on 2026-11-19): that the usual way to make a @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.
Coming next
Personal Catalogue: iOS (Swift & SwiftUI) 5 adds the detail screen: navigating from a row with NavigationStack and navigationDestination, the detail layout, and deleting an item after a confirmation.