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.
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
| Filter | Where it runs | Why |
|---|---|---|
| Search text (title, creator) | In the @Query predicate | Plain string properties; the database does the matching and sorting |
| Type | In memory (Chapter 4) | A handful of items to filter, one optional relationship |
| Tag | In memory | Searching 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
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.)
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:
.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:
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.
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
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 solutionSelect 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 solutionTest 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 solutionChapter 8 Quick Reference
.searchable(text: $model.searchText, prompt: "...")on the container inside theNavigationStack- Dynamic query: a subview whose
initsets_items = Query(filter:sort:order:)from the value passed in - Case-insensitive match in a predicate:
localizedStandardContains; neveruppercased(); capture the search text in a locallet - Keep risky predicates out: filter the to-many
tagsin 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
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.
print calls. (The duplicate warning
is already done in this chapter. Backup comes in Chapter 10.)