Data Model

Personal Catalogue: iOS (Swift & SwiftUI)

Course 1 · Chapter 2 · @Model, Relationships and Delete Rules

Chapter 1 left you with an empty project and a first screen. This chapter writes the shape of the data: three Swift classes that SwiftData will store. There is no container, no query and no screen yet; those come in Chapters 3 and 4. As in the Android course, the model comes first because every later chapter reads or writes it, and changing a stored model after the app is installed means a migration.

What was run, and what was not, and an honest warning about sources
Nothing in this chapter was compiled or run: there is no Mac or Xcode on this machine. More than usual, I could not check this chapter against Apple's own reference pages: my two searches returned the WWDC23 session "Model your schema with SwiftData", Apple developer-forum threads, and third-party articles, and those disagree with each other on how many-to-many relationships declare their inverse. I chose the pattern the sources most agree is safe, and the Not Yet Verified box lists exactly what rests on community reports. Build this chapter early, and trust Xcode's errors over my text.

From Room to SwiftData

If you have read the Android course's Chapter 2, here is the translation. SwiftData needs less code, because it keeps the join between items and tags to itself.

ConceptDjangoAndroid (Room)iOS (SwiftData)
A tablemodels.Model@Entity data class@Model final class
Primary keyAutomatic id@PrimaryKey LongNone to write: every model has a built-in persistentModelID
Optional fieldnull=TrueInt?Int?
Unique valueunique=TrueIndex(unique = true)@Attribute(.unique)
One-to-manyForeignKeyAn id column plus @ForeignKeyA property of the other model's type, e.g. var type: ItemType?
Many-to-manyManyToManyFieldAn explicit cross-reference entityAn array on each side, var tags: [Tag]; the join is automatic
On deleteon_delete=onDelete = CASCADE/RESTRICT@Relationship(deleteRule:)
Creating tablesmigrateGenerated from entities by the database classGenerated from the @Model classes by the container (Chapter 3)

The Three Models

SwiftData models are classes (not structs) marked with the @Model macro, which makes them observable by SwiftUI and storable. Put each in its own file in a Models group in Xcode (right-click the Catalogue folder, New Group, then New File > Swift File). If your wizard generated an Item.swift, replace its contents: its starter Item class has the same name as ours.

ItemType

The fixed lookup list (Book, CD, DVD, Blu-ray) that Chapter 3 will seed. Its name is unique. It also lists its items, and its delete rule is .deny, which makes SwiftData refuse to delete a type that still has items, the same protection as RESTRICT on Android.

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

Tag

A tag is a name, and the spec says "Web Development" and "web development" must be one tag. SwiftData has no equivalent of Room's case-insensitive column setting, so the standard answer is to store two things: the display name the user typed (kept as first typed, so the screen shows "Sci-Fi") and a key, a folded version of it, which is the property marked unique. Two names that fold to the same key are the same tag.

import Foundation import SwiftData @Model final class Tag { /// What the user typed, cleaned up: "Sci-Fi". var name: String /// The folded form used for uniqueness: "sci-fi". Never shown. @Attribute(.unique) var key: String /// The other side of Item.tags. Declared plainly; the inverse is declared on Item. var items: [Item] = [] init(name: String) { let cleaned = Tag.cleaned(name) self.name = cleaned self.key = Tag.key(for: cleaned) } /// Trims the name and turns any run of whitespace into one space. static func cleaned(_ raw: String) -> String { raw.split(whereSeparator: \.isWhitespace).joined(separator: " ") } /// The uniqueness key: cleaned, then folded for case and accents. static func key(for raw: String) -> String { cleaned(raw).folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil) } }

Two things to notice. Foundation's folding is Unicode-aware: "Café" and "cafe" fold to the same key, which the Android version's ASCII-only NOCASE could not do. Whether that is what you want is a design choice (Exercise 3 asks you to decide), but it is available. And the key must always be produced from the name by Tag.key(for:), never typed in by hand, or the two can drift apart.

Item

The main model. It holds a to-one relationship to its type and a many-to-many relationship to its tags.

import Foundation import SwiftData @Model final class Item { var title: String var creator: String var formatDetail: String var releaseYear: Int? var notes: String var createdAt: Date var type: ItemType? @Relationship(inverse: \Tag.items) var tags: [Tag] = [] init( title: String, creator: String = "", formatDetail: String = "", releaseYear: Int? = nil, notes: String = "", createdAt: Date = .now, type: ItemType? ) { self.title = title self.creator = creator self.formatDetail = formatDetail self.releaseYear = releaseYear self.notes = notes self.createdAt = createdAt self.type = type } }

Three decisions. type is optional because SwiftData's to-one relationships are, so "every item has a type" becomes a rule your own code (the form, in Chapter 6) must enforce rather than something the database does. createdAt is a Date, which SwiftData stores directly (Room needed a Long). And there is no id: each model instance already has a persistentModelID, which Chapter 5 will use to say which item to show.

The Many-to-Many, and Why Only One Side Declares the Inverse

The tag relationship is the part of this chapter you should read twice, because it is where the sources disagree. The facts, as best I could establish them:

  • A many-to-many relationship in SwiftData is just an array on each side: Item.tags and Tag.items. SwiftData creates the join storage; you never see a link table (unlike Room's cross-reference entity).
  • Some sources say SwiftData infers the inverse when at least one end is optional; others say it never infers a many-to-many inverse and you must declare it; another reports that for many-to-many the inverse can only be declared on one side. Apple's own forum has a many-to-many question that ends in a "Failed to fulfill link" error.
  • The pattern all of those allow is the one used above: @Relationship(inverse: \Tag.items) on Item.tags only, both properties arrays with a default of [].

In Chapter 3 you will build a container and insert real data; that is the first time the relationship is actually exercised, so if it misbehaves, the first thing to try is moving the inverse declaration to the other side or declaring it explicitly on both, and re-reading Apple's current Relationship documentation, which I could not.

Delete Rules in This Model

SwiftData's @Relationship(deleteRule:) decides what happens to the other side when an object is deleted. The WWDC23 session and forum posts agree that the default is nullify: the relationship is simply cleared. That default is exactly what we want for tags, and the explicit .deny is what we want for types.

You deleteRuleEffectAndroid equivalent
An itemDefault (nullify)It disappears from every tag's items; the tags stayCASCADE on the link rows
A tagDefault (nullify)It disappears from every item's tags; the items stayCASCADE on the link rows
An item type that has items.denyThe delete is refusedRESTRICT

Be careful with the one rule you might be tempted to add: .cascade on Tag.items would delete every item carrying a deleted tag, which is almost never wanted. Several forum threads also report cascade rules failing in some situations (one links it to declaring an inverse; another to saving the context explicitly), so cascade is a rule to test, not to assume. We have no need for it.

Helper Properties

Screens will constantly want a tag list in alphabetical order and a type name that is not optional. Put those once on the model, as computed properties, and add them to the end of Item:

extension Item { /// "Book", "CD"... or an empty string if (against the rules) there is no type. var typeName: String { type?.name ?? "" } /// The item's tags in alphabetical order, ignoring case. var sortedTags: [Tag] { tags.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending } } }

Computed properties are not stored, so adding or changing them never needs a migration; only changes to stored properties do.

Why Models, Not an Enum, for ItemType
Swift makes an enum ItemType: String, Codable very easy, and for a list that never changes it would be simpler, with no seeding, no relationship and no delete rule. This course keeps ItemType a model for two reasons: the spec lists it as a table so that the two mobile courses mirror each other, and a model is the version that survives the roadmap, where a user might add their own types (vinyl, board games) without a new app release. If you prefer the enum, everything in Chapters 3 to 10 gets shorter, and that is a perfectly good variation to try.
Compare with the Android course
Personal Catalogue: Android (Kotlin & Compose) Chapter 2 builds the same data with four classes instead of three: its ItemTagCrossRef is the join that SwiftData hides. Android makes the id, the foreign key, the indices and the unique rules explicit and checks them when the project builds; SwiftData infers most of them from the properties and relationships. The cost of that brevity is the one this chapter has been warning about: more of the behaviour is implicit, so more of it has to be tested by running the app.

Challenges

Exercise 1

Create the three model files and the helper extension, delete any wizard-generated Item.swift that conflicts, and build the project (Product > Build). Write down every error or warning and which line it pointed at. If the build succeeds, note that a successful build does not yet prove the relationship works; say why.

📄 View solution
Exercise 2

Sketch the stored objects after you add a book "Dune" tagged sci-fi and classic, and a DVD "Alien" tagged sci-fi. Say what each object's relationship properties contain. Then say what changes if you delete the tag sci-fi, what changes if you delete "Dune", and what should happen if you try to delete the type DVD.

📄 View solution
Exercise 3

Work out by hand what Tag.cleaned and Tag.key(for:) return for: " Sci-Fi ", "sci fi", "SCI-FI", "Café" and "cafe". Decide whether "Café" and "cafe" should be the same tag, and say what you would change in key(for:) if not. Finally, explain what a unique key means for the line context.insert(Tag(name: "SCI-FI")) when "Sci-Fi" already exists.

📄 View solution

Chapter 2 Quick Reference

  • Model: @Model final class X { ... } with a designated init; no id to write (each has persistentModelID)
  • Optional field: var releaseYear: Int?; unique value: @Attribute(.unique)
  • To-one relationship: var type: ItemType? (always optional); to-many: var items: [Item] = []
  • Many-to-many: an array on each side; declare @Relationship(inverse: \Tag.items) on one side only (the safest pattern across sources: test it)
  • Delete rules: default nullify (clears the link); .deny refuses deletion while related objects exist; avoid .cascade on tags
  • Case-insensitive unique names: store a folded key (folding(options: [.caseInsensitive, .diacriticInsensitive], locale: nil)) and mark it unique
  • Computed properties (typeName, sortedTags) are free: no migration
Not Yet Verified
Checked (two web searches on 2026-11-19), and only through secondary sources: that the WWDC23 session and forum posts describe nullify as the default delete rule, with cascade available by adding @Relationship; that third-party notes on the WWDC23 session say @Attribute(.unique) makes an insert update an existing record with the same value; that sources conflict about inferring many-to-many inverses (one says inferred when an end is optional, one says never inferred, one says the inverse may only be set on one side); that Apple's forum has a many-to-many "Failed to fulfill link" error report; and that some forum posts report cascade failing in certain setups.
Not checked at all, from general knowledge: that .deny exists as a delete rule and behaves as described (it was not in the search results); that the @Relationship(inverse: \Tag.items) key-path syntax is right for your SwiftData version; the Foundation folding(options:locale:) behaviour on your strings; that a unique key plus a plain name is how to get case-insensitive uniqueness (my design, not a documented recipe); that final class is required; the minimum OS version; and all code, none of which was compiled. I did not consult Apple's documentation pages for Relationship, Attribute or Model: please read them.
Coming next
Personal Catalogue: iOS (Swift & SwiftUI) 3 builds the persistence layer: the model container that creates the store, seeding the four item types on first launch, a small repository for the rules that are more than one line, and SwiftUI previews that run on an in-memory store.