Persistence Layer
Personal Catalogue: iOS (Swift & SwiftUI)
Course 1 ยท Chapter 3 ยท Container, Seeding, Repository and Previews
Chapter 2 described the data; this chapter makes it real. You will create the model container that opens the SwiftData store, seed the four item types on first launch, write a small repository for the rules that are more than one line (saving an item with its tags, finding or creating a tag), and set up previews that run on an in-memory store so that SwiftUI's canvas never touches your real data. By the end the app can store and load a catalogue, though nothing on screen uses it until Chapter 4.
ModelContext.save(), fetchCount or transactions, so those are from my memory.
The Not Yet Verified box separates what the sources showed from what I assumed. As in Chapter 2: build early, and trust Xcode's errors over my text.
What Is Different from Android Here
Room needed a lot of machinery in this layer: DAO interfaces, a database class, a Hilt module. SwiftData has far less, because a SwiftUI view reads data with @Query (Chapter 4) and writes through a
ModelContext that SwiftUI puts in the environment. So this chapter is shorter, and the repository is smaller: it holds only the write rules.
| Job | Android (Room + Hilt) | iOS (SwiftData) |
|---|---|---|
| Opening the database | AppDatabase built in a Hilt module | A ModelContainer built once, attached to the app |
| Reading | DAO methods returning Flow | @Query in the view (Chapter 4) |
| Writing | DAO @Insert/@Update/@Delete | context.insert, changing a property, context.delete |
| Getting the connection to a screen | Hilt injection | @Environment(\.modelContext) |
| Several writes as one unit | db.withTransaction { } | Make the changes, then try context.save() once |
| Seeding | ensureSeeded() on startup | The same function, on startup |
| Previews | Preview with made-up data | Preview with an in-memory container |
Step 1: Add an Order to ItemType
One correction to Chapter 2. Room sorted the types by their auto-generated id, which follows insertion order. SwiftData gives you no such id to sort by, and a query with no sort has no guaranteed order, so the
four types need an explicit sortOrder. Change ItemType to:
You are changing a stored property, which on an installed app would need a migration. You have nothing installed that matters yet, so simply delete the app from the simulator (long-press its icon and remove it) before the next run. This is the same lesson as Android's "raise the database version": once real data exists, model changes are expensive, which is why Chapter 2 was careful.
Step 2: The Container
A ModelContainer is the object that owns the store on disk. It is created from a schema, the list of model classes. Put the list in one place, because the app, the previews and (in Chapter
10) the tests all need the same list. Create Persistence.swift:
isStoredInMemoryOnly: true is what the tutorials in my search use for previews: the store lives only in memory, so nothing is written to disk and nothing survives. Now the app file. If the
wizard generated its own sharedModelContainer code, replace it with this:
.modelContainer(container) attaches the container to the window, which does two things: every view inside can use @Query, and each gets a ModelContext from the
environment. (A shorter .modelContainer(for: [Item.self, ...]) exists and builds the container for you, but then you cannot reuse the same container setup for previews and tests.) A
fatalError if the store will not open is crude, but at this point in a launch there is nothing sensible to show; it is a known placeholder, not the final design.
Step 3: The Repository
A ModelContext is SwiftData's unit of work: you insert and change objects in it, and it writes them to the store when saved. The repository is a small struct wrapping one. Create
CatalogueRepository.swift:
Four things in that file deserve explanation.
- Why
tag(named:)looks before it inserts. Chapter 2's third exercise warned that, according to a secondary source, inserting a model whose@Attribute(.unique)value already exists may update the existing record instead of failing. Looking up by key first means we never rely on that: an existing tag is returned untouched, and its spelling stays as first typed. - The local
keyconstant. The#Predicatemacro builds a query that SwiftData translates for the store, so it can only use simple expressions and values captured from outside. CallingTag.key(for:)inside the predicate would not be allowed; computing it first and capturing the constant is the usual approach. - "Insert before relationships." A common recommendation in tutorials and forum posts is to insert a new model into the context before assigning relationships to it, which
save(_:tagNames:)does. I could not confirm it from Apple's documentation, but it costs nothing. - No separate transaction. Everything between the first change and
context.save()is one unit of work: nothing reaches the store untilsave(). That is the SwiftData counterpart of Chapter 7'swithTransactionon Android, but it depends on you callingsave()once at the end, which is why the repository does it for every write. (SwiftData's main context may also save automatically; the unit of work still ends when the function returns, because nothing here awaits.)
Step 4: Seeding at Launch
Seeding needs a context, and the cleanest place to get one is a view, via the environment. Create a RootView that every later screen will sit inside, and that seeds as it appears:
.task runs when the view appears. Because screens read with @Query, which updates automatically, it does not matter that seeding finishes a moment after the first frame: the type
chips and the type picker simply fill in. The repository is a cheap struct, so each screen can make one from its own modelContext when it needs one; there is no dependency-injection library
and no singleton.
Step 5: Previews on an In-Memory Store
A SwiftUI preview runs your view in Xcode's canvas, and a view that uses @Query needs a container to run at all. Never point a preview at the real store. The tutorials in my search agree on a
pattern: build one shared in-memory container, fill it with sample data, and pass it to each preview. They also report that creating a fresh container inside every #Preview block can
crash the canvas, which is the reason for sharing one.
The try! is acceptable here and nowhere else: this code only ever runs in the canvas, and a crash there is the quickest way to tell you the model is wrong. Use it in any preview like this:
The sample data also runs the repository's own code (seeding, tag(named:), saving with relationships), so the canvas becomes a quick, free test of the Chapter 2 relationship: if the many-to-many
inverse is wrong, this is where it should fail, loudly, before you have written a single screen.
Step 6: See It Work
You have no list screen yet, so replace ContentView with a temporary one that shows the stored item types. It uses @Query, the way Chapter 4's list will:
Run in the simulator: you should see Book, CD, DVD and Blu-ray, in that order, and an empty tags section. Quit and run again: still four types, not eight, because ensureSeeded() counts first. The
canvas preview should additionally show the three sample tags, sci-fi, classic and jazz, with sci-fi appearing once even though two items use it.
Challenges
Make all the changes (sortOrder, Persistence, the app file, the repository, RootView, PreviewData, the temporary ContentView),
delete the old app from the simulator, and run. Record what you see on first launch, after a relaunch, and in the canvas preview. List every build or run-time error you had and what caused it.
Prove that tag(named:) never creates duplicates. Add a temporary button to ContentView that calls tag(named:) with "Sci-Fi", then "SCI-FI", then
" sci-fi " and saves. Predict how many tags exist and what name it shows, then run it and compare. Explain what would be different if the function simply did context.insert(Tag(name: name)).
Chapter 2 gave ItemType.items the delete rule .deny, and its sources never confirmed it. Test it now: in the preview or a temporary button, try to delete the type
"Book" while "Dune" uses it. Record exactly what happens (an error, a crash, nothing, or the type deleted anyway) and when it happens (at delete or at save). Then say what the
repository should do about it.
Chapter 3 Quick Reference
- Container:
ModelContainer(for: schema, configurations: [ModelConfiguration(schema:, isStoredInMemoryOnly:)]); attach with.modelContainer(container); keep the model list in one place (Persistence.schema) - Context:
@Environment(\.modelContext); write withinsert, property changes,delete, thentry context.save() - Read once:
context.fetch(FetchDescriptor<T>(predicate:, sortBy:)),fetchCount; read live in views with@Query(Chapter 4) - Predicates use captured constants, not calls to your own functions:
let key = Tag.key(for: name); #Predicate { $0.key == key } - Insert a new model before assigning its relationships
- Seed idempotently: count first, insert only when empty; give types an explicit
sortOrder - Find-or-create tags by key; never insert a tag without looking first
- Previews: one shared in-memory, seeded container (
PreviewData.container), never the real store
ModelConfiguration with in-memory storage keeps preview data off disk; that the
common preview pattern is a shared, @MainActor container filled via mainContext and passed with .modelContainer(...); that one tutorial checks whether the store is empty
with a FetchDescriptor before seeding; that creating a new container inside each #Preview has been reported to crash; and that on macOS with iCloud an in-memory setting needed
cloudKitDatabase: .none (not relevant to an iPhone app with no iCloud).Not checked, from general knowledge:
ModelContext.save(), fetchCount, insert and delete semantics; fetchLimit;
#Predicate capturing a local constant; the exact initialisers of Schema, ModelConfiguration and ModelContainer in your SDK; that modelContainer(_:) accepts a
container instance; whether the main context autosaves in a way that could save part of a multi-step change; "insert before assigning relationships" (a tutorial convention, not a documented rule);
@MainActor and Swift-concurrency behaviour of App.init and mainContext under your Xcode's language mode; that @Model types work as
ForEach content without an explicit id; the .deny rule (see Exercise 3); and all code, none of which was compiled. I did not consult Apple's reference
pages for any of these APIs.
@Query sorted newest first, the type filter, rows showing title, creator and tags, an empty state, and the
@Observable view model that holds the filter choice.