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.

What was run, and what was not, and what the sources are
Nothing in this chapter was compiled or run: there is no Mac or Xcode on this machine. My search for this chapter returned tutorials (Kodeco, AppCoda, Hacking with Swift forum posts) and Apple developer-forum threads, not Apple's reference pages, and found nothing on 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.

JobAndroid (Room + Hilt)iOS (SwiftData)
Opening the databaseAppDatabase built in a Hilt moduleA ModelContainer built once, attached to the app
ReadingDAO methods returning Flow@Query in the view (Chapter 4)
WritingDAO @Insert/@Update/@Deletecontext.insert, changing a property, context.delete
Getting the connection to a screenHilt injection@Environment(\.modelContext)
Several writes as one unitdb.withTransaction { }Make the changes, then try context.save() once
SeedingensureSeeded() on startupThe same function, on startup
PreviewsPreview with made-up dataPreview 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:

@Model final class ItemType { @Attribute(.unique) var name: String var sortOrder: Int @Relationship(deleteRule: .deny, inverse: \Item.type) var items: [Item] = [] init(name: String, sortOrder: Int) { self.name = name self.sortOrder = sortOrder } }

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:

import Foundation import SwiftData enum Persistence { /// Every model the store knows about. Add new models here, and only here. static let schema = Schema([Item.self, ItemType.self, Tag.self]) /// A container on disk for the real app, or in memory for previews and tests. static func makeContainer(inMemory: Bool = false) throws -> ModelContainer { let configuration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: inMemory) return try ModelContainer(for: schema, configurations: [configuration]) } }

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:

import SwiftUI import SwiftData @main struct CatalogueApp: App { private let container: ModelContainer init() { do { container = try Persistence.makeContainer() } catch { // Placeholder. Chapter 9 replaces this with a screen that explains the problem. fatalError("Could not open the catalogue store: \(error)") } } var body: some Scene { WindowGroup { RootView() } .modelContainer(container) } }

.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:

import Foundation import SwiftData @MainActor struct CatalogueRepository { let context: ModelContext // MARK: Item types /// Call at every launch. Inserts the four types only if there are none. func ensureSeeded() throws { let existing = try context.fetchCount(FetchDescriptor<ItemType>()) guard existing == 0 else { return } for (index, name) in ["Book", "CD", "DVD", "Blu-ray"].enumerated() { context.insert(ItemType(name: name, sortOrder: index)) } try context.save() } func itemTypes() throws -> [ItemType] { try context.fetch(FetchDescriptor<ItemType>(sortBy: [SortDescriptor(\.sortOrder)])) } // MARK: Tags /// The existing tag with this name (in any case), or a new one. Never inserts a duplicate. func tag(named rawName: String) throws -> Tag? { let cleaned = Tag.cleaned(rawName) guard !cleaned.isEmpty else { return nil } let key = Tag.key(for: cleaned) // a local constant: predicates cannot call our functions var descriptor = FetchDescriptor<Tag>(predicate: #Predicate { $0.key == key }) descriptor.fetchLimit = 1 if let found = try context.fetch(descriptor).first { return found } let created = Tag(name: cleaned) context.insert(created) return created } // MARK: Items /// Saves a new or edited item together with its tags, in one save. func save(_ item: Item, tagNames: [String]) throws { if item.modelContext == nil { context.insert(item) // insert BEFORE setting relationships } var tags: [Tag] = [] for name in tagNames { if let tag = try tag(named: name), !tags.contains(where: { $0.key == tag.key }) { tags.append(tag) } } item.tags = tags try context.save() } func delete(_ item: Item) throws { context.delete(item) try context.save() } }

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 key constant. The #Predicate macro builds a query that SwiftData translates for the store, so it can only use simple expressions and values captured from outside. Calling Tag.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 until save(). That is the SwiftData counterpart of Chapter 7's withTransaction on Android, but it depends on you calling save() 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:

import SwiftUI import SwiftData struct RootView: View { @Environment(\.modelContext) private var context var body: some View { ContentView() .task { do { try CatalogueRepository(context: context).ensureSeeded() } catch { print("Seeding failed: \(error)") // Chapter 9 shows this to the user } } } }

.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.

import Foundation import SwiftData @MainActor enum PreviewData { /// One shared, seeded, in-memory container for every preview. static let container: ModelContainer = { let container = try! Persistence.makeContainer(inMemory: true) let repo = CatalogueRepository(context: container.mainContext) try! repo.ensureSeeded() let types = try! repo.itemTypes() // Book, CD, DVD, Blu-ray let samples: [(String, String, Int, Int, [String])] = [ ("Dune", "Frank Herbert", 1965, 0, ["sci-fi", "classic"]), ("Kind of Blue", "Miles Davis", 1959, 1, ["jazz"]), ("Alien", "Ridley Scott", 1979, 2, ["sci-fi"]) ] for (title, creator, year, typeIndex, tags) in samples { let item = Item(title: title, creator: creator, releaseYear: year, type: types[typeIndex]) try! repo.save(item, tagNames: tags) } return container }() }

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:

#Preview { ContentView() .modelContainer(PreviewData.container) }

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:

import SwiftUI import SwiftData // TEMPORARY: Chapter 4 replaces this with the real list screen. struct ContentView: View { @Query(sort: \ItemType.sortOrder) private var types: [ItemType] @Query private var tags: [Tag] var body: some View { List { Section("Item types") { ForEach(types) { Text($0.name) } } Section("Tags") { ForEach(tags) { Text($0.name) } } } } } #Preview { ContentView() .modelContainer(PreviewData.container) }

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.

Compare with the Android course
In Personal Catalogue: Android (Kotlin & Compose) Chapter 3, this layer was five Kotlin files plus Gradle and Hilt setup, and the compiler checked the queries. Here it is three small files and a couple of modifiers, but the checking happens at run time, and the sample-data preview is how you catch mistakes early. The repository functions are the same ideas in both courses: seed on launch, find-or-create a tag by its normalised name, and save an item with its tags as one unit.

Challenges

Exercise 1

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.

๐Ÿ“„ View solution
Exercise 2

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)).

๐Ÿ“„ View solution
Exercise 3

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.

๐Ÿ“„ View solution

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 with insert, property changes, delete, then try 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
Not Yet Verified
Checked (one web search on 2026-11-19), through tutorials and forum posts only: that a 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.
Coming next
Personal Catalogue: iOS (Swift & SwiftUI) 4 builds the list screen: an @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.