Search and Filter

Personal Catalogue: iOS (Swift & SwiftUI)

Course 1 · Chapter 8 · Search, Tag Filter and "Do I Own This?"

A catalogue is only useful if you can find things in it, and its most common real-world question is "do I already own this?". This chapter adds a search bar, a tag filter and a duplicate warning in the add form. It is also where Chapter 4's promise is kept: the search text goes into the database query, using the dynamic-@Query pattern that Chapter 4 explained but deliberately avoided.

What was run, and what was not
Nothing in this chapter was compiled or run (no Mac or Xcode here). My search confirmed that localizedStandardContains is the usual case-insensitive match inside a #Predicate, that uppercased() inside one crashes at runtime, and that optional to-many relationships in a predicate have caused crashes. It did not cover .searchable, and it did not say whether localizedStandardContains ignores accents, so that is from memory and flagged below. This chapter's predicate touches only title and creator, which are plain non-optional strings: that is a deliberate choice, explained next.

What Goes in the Query and What Does Not

FilterWhere it runsWhy
Search text (title, creator)In the @Query predicatePlain string properties; the database does the matching and sorting
TypeIn memory (Chapter 4)A handful of items to filter, one optional relationship
TagIn memorySearching a to-many relationship inside a predicate is where my sources report crashes; filtering the fetched array is safe

This split is a judgement, not a rule. For a personal catalogue of hundreds of items, filtering the result of a text query in memory costs nothing, and it keeps the risky predicate shapes out of the app. If you ever need the tag filter in the database too, test it carefully on your OS versions first; the forum reports I found suggest making the relationship non-optional (ours already is: tags: [Tag] = []).

Step 1: Extend the View Model

@Observable final class ListViewModel { var selectedTypeName: String? var selectedTagKey: String? // the folded key of the chosen tag; nil = any var searchText = "" var hasFilters: Bool { selectedTypeName != nil || selectedTagKey != nil || !searchText.isEmpty } /// Applies the type and tag filters to an already-searched, already-sorted list. func filtered(_ items: [Item]) -> [Item] { items.filter { item in (selectedTypeName == nil || item.type?.name == selectedTypeName) && (selectedTagKey == nil || item.tags.contains { $0.key == selectedTagKey }) } } }

Step 2: A List That Rebuilds Its Query

A @Query cannot read a changing value directly, so move the list into its own view whose init builds the query from the search text it is given. SwiftUI re-creates that view each time the text changes, which is how the sources describe it working. (An Apple forum reply says SwiftData assumes a re-fetch each time the init runs, so pass in only what the query needs, as here.)

import SwiftUI import SwiftData struct ItemListContent: View { @Query private var items: [Item] let model: ListViewModel let catalogueIsEmpty: Bool let searchText: String let onAddNew: (String) -> Void init(model: ListViewModel, searchText: String, catalogueIsEmpty: Bool, onAddNew: @escaping (String) -> Void) { self.model = model self.searchText = searchText self.catalogueIsEmpty = catalogueIsEmpty self.onAddNew = onAddNew let term = searchText let predicate: Predicate<Item> = term.isEmpty ? #Predicate<Item> { _ in true } : #Predicate<Item> { $0.title.localizedStandardContains(term) || $0.creator.localizedStandardContains(term) } _items = Query(filter: predicate, sort: \Item.createdAt, order: .reverse) } private var shown: [Item] { model.filtered(items) } var body: some View { if catalogueIsEmpty { ContentUnavailableView("Your catalogue is empty", systemImage: "books.vertical", description: Text("Tap + to add your first item.")) } else if shown.isEmpty { VStack(spacing: 12) { if !searchText.isEmpty { ContentUnavailableView.search(text: searchText) Button("Add \"\(searchText)\"") { onAddNew(searchText) } .buttonStyle(.borderedProminent) } else { ContentUnavailableView("Nothing matches these filters", systemImage: "line.3.horizontal.decrease.circle", description: Text("Choose All to see everything.")) } } } else { List { ForEach(shown) { item in NavigationLink(value: item) { ItemRow(item: item) } } } } } }

The "no results" state is the "do I own this?" answer in its first form: search "Dune", see nothing, and a button offers to add "Dune" with the title already filled in. ContentUnavailableView.search(text:) is the system's ready-made no-results view. catalogueIsEmpty comes from the parent, because this view's own query is filtered and so cannot tell "nothing exists" from "nothing matches".

Step 3: The Parent Screen

ListView now owns the search field and the tag row, passes the text down, and keeps a plain unfiltered @Query of all items, used only to know whether the catalogue is empty and which tags are in use. (A second fetch of everything is fine at this size.) Replace the old body with:

struct ListView: View { @Query private var allItems: [Item] @Query(sort: \ItemType.sortOrder) private var types: [ItemType] @State private var model = ListViewModel() @State private var showAdd = false @State private var addTitle = "" // Tags that at least one item uses, in name order. private var tagsInUse: [Tag] { var seen = Set<String>() return allItems.flatMap(\.tags) .filter { seen.insert($0.key).inserted } .sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } } var body: some View { NavigationStack { VStack(spacing: 0) { TypeFilterRow(types: types, selected: $model.selectedTypeName) TagFilterRow(tags: tagsInUse, selectedKey: $model.selectedTagKey) ItemListContent(model: model, searchText: model.searchText, catalogueIsEmpty: allItems.isEmpty) { title in addTitle = title showAdd = true } } .navigationTitle("My Catalogue") .searchable(text: $model.searchText, prompt: "Title or creator") .navigationDestination(for: Item.self) { item in DetailView(item: item) } .toolbar { ToolbarItem(placement: .primaryAction) { Button("Add", systemImage: "plus") { addTitle = ""; showAdd = true } } } .sheet(isPresented: $showAdd) { ItemFormView(item: nil, initialTitle: addTitle) } } } } struct TagFilterRow: View { let tags: [Tag] @Binding var selectedKey: String? var body: some View { if !tags.isEmpty { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 8) { FilterChip(title: "Any tag", isSelected: selectedKey == nil) { selectedKey = nil } ForEach(tags) { tag in FilterChip(title: tag.name, isSelected: selectedKey == tag.key) { selectedKey = tag.key } } } .padding(.horizontal) .padding(.bottom, 8) } } } }

.searchable adds a search field that sits in the navigation bar and binds to the model's searchText. The tag row reuses Chapter 4's FilterChip and lists only tags that items really use, which also solves the orphan question left open in Chapter 7. If the chosen tag stops being used (its last item is deleted or retagged), the filter would silently hide everything: Exercise 2 asks you to handle that.

Step 4: "Do I Already Own This?" in the Form

The shared spec says a possible duplicate (same title and creator) is a warning, never a block: you may genuinely own two copies, or a book and its film. Add the starting title to the form and a warning footer. In ItemFormView:

// 1. New init parameter and an all-items query for the check: @Query private var allItems: [Item] init(item: Item?, initialTitle: String = "") { self.item = item var start = item.map(ItemDraft.init(item:)) ?? ItemDraft() if item == nil { start.title = initialTitle } _draft = State(initialValue: start) } // 2. The check: same folded title and creator, and not the item being edited. private var duplicates: [Item] { let title = Tag.key(for: draft.title) let creator = Tag.key(for: draft.creator) guard !title.isEmpty else { return [] } return allItems.filter { $0 !== item && Tag.key(for: $0.title) == title && Tag.key(for: $0.creator) == creator } } // 3. In the title section's footer, after the error text: if !duplicates.isEmpty { Label("You may already own this (\(duplicates.count) match). You can still save it.", systemImage: "exclamationmark.triangle") .foregroundStyle(.orange) }

It reuses Tag.key(for:) because that function already folds case and accents, and I am borrowing it for general strings; a clearer design would rename it to a shared fold(_:). The warning appears as soon as both fields match an existing item, and Save is untouched, which is exactly the "never a block" rule. $0 !== item excludes the item being edited, so editing never warns about itself.

Compare with the Android course
Personal Catalogue: Android (Kotlin & Compose) Chapter 8 used debounce and flatMapLatest to turn typing into queries without hammering the database. Here the equivalent is implicit: SwiftUI rebuilds the list view when the text changes, and the search happens in a fetch you never see. You gain simplicity and lose control: there is no debounce knob, so the sources' warning about re-fetching on every init is the thing to watch on a large store. The duplicate rule is the same in both courses, and the Android SQLite NOCASE limit is again avoided here by folding in code.

Challenges

Exercise 1

Make the changes, then add "Dune" by Frank Herbert and "Kind of Blue" by Miles Davis (tag the first "Sci-Fi"). Search "dune", "HERBERT", "blue" and "xyz". Write down what each shows. Then add "dune" by "frank herbert" and describe the warning.

📄 View solution
Exercise 2

Select a tag in the filter row, then delete the only item carrying it. The list now shows "Nothing matches these filters" with no chip highlighted. Explain why, and fix it so the filter resets automatically.

📄 View solution
Exercise 3

Test whether your search ignores accents: add an item titled "Café Society" and search "cafe", then add "Cafe Society" and "café" in turn. Record the results and the iOS version. Then say whether the duplicate check (which folds in code) and the search (which uses the database) agree, and why that could matter.

📄 View solution

Chapter 8 Quick Reference

  • .searchable(text: $model.searchText, prompt: "...") on the container inside the NavigationStack
  • Dynamic query: a subview whose init sets _items = Query(filter:sort:order:) from the value passed in
  • Case-insensitive match in a predicate: localizedStandardContains; never uppercased(); capture the search text in a local let
  • Keep risky predicates out: filter the to-many tags in memory
  • ContentUnavailableView.search(text:) for no results; offer "Add ..." with the typed text
  • Duplicate = same folded title and creator, excluding the item being edited; a warning, never a block
Not Yet Verified
Checked (one web search on 2026-11-19): that localizedStandardContains is the usual case-insensitive text match in a #Predicate, with a forum example; that it and contains on collections are listed among supported predicate operations by a third-party skill reference; that uppercased() in a predicate crashes at runtime; and that optional to-many relationships in predicates have been reported to crash, with making the relationship non-optional as a reported fix.
Not checked, from general knowledge: that localizedStandardContains ignores accents (the search did not say; Exercise 3 tests it); .searchable and where to attach it; the ternary choosing between two #Predicate values (if Xcode objects, use two initialisers or one predicate with the empty case folded in); Query(filter:sort:order:) with a Predicate?; ContentUnavailableView.search(text:); that the rebuilt view re-queries on each text change; $0 !== item identity comparison for models; and all code, none of which was compiled. I did not consult Apple's reference pages.
Coming next
Personal Catalogue: iOS (Swift & SwiftUI) 9 adds polish: a light and dark appearance check, VoiceOver and Dynamic Type, and real error handling to replace the print calls. (The duplicate warning is already done in this chapter. Backup comes in Chapter 10.)