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.
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.
| Concept | Django | Android (Room) | iOS (SwiftData) |
|---|---|---|---|
| A table | models.Model | @Entity data class | @Model final class |
| Primary key | Automatic id | @PrimaryKey Long | None to write: every model has a built-in persistentModelID |
| Optional field | null=True | Int? | Int? |
| Unique value | unique=True | Index(unique = true) | @Attribute(.unique) |
| One-to-many | ForeignKey | An id column plus @ForeignKey | A property of the other model's type, e.g. var type: ItemType? |
| Many-to-many | ManyToManyField | An explicit cross-reference entity | An array on each side, var tags: [Tag]; the join is automatic |
| On delete | on_delete= | onDelete = CASCADE/RESTRICT | @Relationship(deleteRule:) |
| Creating tables | migrate | Generated from entities by the database class | Generated 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.
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.
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.
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.tagsandTag.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)onItem.tagsonly, 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 delete | Rule | Effect | Android equivalent |
|---|---|---|---|
| An item | Default (nullify) | It disappears from every tag's items; the tags stay | CASCADE on the link rows |
| A tag | Default (nullify) | It disappears from every item's tags; the items stay | CASCADE on the link rows |
| An item type that has items | .deny | The delete is refused | RESTRICT |
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:
Computed properties are not stored, so adding or changing them never needs a migration; only changes to stored properties do.
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.
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
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.
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 solutionWork 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.
Chapter 2 Quick Reference
- Model:
@Model final class X { ... }with a designatedinit; no id to write (each haspersistentModelID) - 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);
.denyrefuses deletion while related objects exist; avoid.cascadeon 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
@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.