skip to content

In SwiftData, how do you declare that a Project model owns many Task models, with each task pointing back to its project?

level: juniorimportance: must knowfreq 65%

answer

  1. the property's type makes the link
  2. an array on one side
  3. an optional back-reference
  4. inverse key path, one side only

basics

~20 s

Give Project an array property of the task model and give the task an optional Project property. Name the pairing with @Relationship(inverse:) on one of the two, and SwiftData keeps both ends of the link in sync.

solid answer

~40 s

In SwiftData any stored property whose type is another model, or an array of models, is a relationship. `Project` gets `var tasks: [ProjectTask] = []` and the task gets `var project: Project?`, optional because a task can exist on its own and because the default delete rule sets it to `nil`. The two properties are each other's **inverse**: declare that with `@Relationship(inverse: \ProjectTask.project)` on one side only, or let SwiftData infer it, which it does for a single one-to-one or one-to-many pair. With the inverse known, setting `task.project = project` puts the task into `project.tasks` straight away, before any save. `ModelContainer(for: Project.self)` is enough, because SwiftData follows relationships to include `ProjectTask` in the schema. A user with an optional profile is the same idea with an optional property on each side.

code

swift · 24 lines
swift
import SwiftData

@Model
final class Project {
    var name: String
    @Relationship(inverse: \ProjectTask.project)
    var tasks: [ProjectTask] = []

    init(name: String) { self.name = name }
}

@Model
final class ProjectTask {
    var title: String
    var project: Project?   // optional: a task can exist without a project

    init(title: String) { self.title = title }
}

func addTask(titled title: String, to project: Project, in context: ModelContext) {
    let task = ProjectTask(title: title)
    context.insert(task)
    task.project = project   // SwiftData adds task to project.tasks as well
}

go deeper

for a junior

Recall the two properties: an array of tasks on the project and an optional project on the task. Be ready to say what the inverse is and that SwiftData keeps both ends in sync.

for a middle

Explain when SwiftData infers the inverse and when you must declare it, why the back-reference is optional, and why the container needs only the root model type.

for a senior

Show the habits you would enforce in review: inverse declared once and explicitly, no hand-kept foreign-key attributes, and a back-reference type that matches the delete rule chosen for it.

for a principal

Treat the relationship shape as part of the persisted schema: changing it later means a migration, so settle ownership, optionality and naming before the first release ships.

## What a relationship is in SwiftData A **relationship** is a stored property of a `@Model` class whose type is another model (a **to-one** relationship) or an array of models (a **to-many** relationship). SwiftData recognises it from the type alone: Apple's documentation says that when a model contains a property whose type is also a model, or a collection of models, the framework manages the relationship for you. The `@Relationship` macro is only needed to set options on it: the delete rule, the inverse, the model-count limits or a former name. In a project-management app a `Project` owns many tasks and each task belongs to at most one project. That is the classic **one-to-many** shape: - `Project.tasks` is the to-many side, declared as `[ProjectTask]` with a default of `[]`. - `ProjectTask.project` is the to-one side, declared as `Project?`, because a task can be created before it is filed and because deleting a project with the default rule sets this property to `nil`. - The model is called `ProjectTask` rather than `Task`: a type named `Task` in your module would shadow Swift's concurrency `Task` type everywhere in it. ## The inverse: one link seen from both ends Two properties that describe the same link from opposite ends are each other's **inverse**. When SwiftData knows the inverse, it maintains both ends for you. Set `task.project = project` and `project.tasks` contains the task immediately, while the change is still unsaved; append a task to `project.tasks` and its `project` points back. There are two ways to give SwiftData the inverse: 1. **Declare it** with `@Relationship(inverse: \ProjectTask.project)` on one of the two properties. Either side works: Apple's own samples put it on the to-many side in one place and on the to-one side in another. 2. **Let SwiftData infer it.** Apple's documentation says the framework sets the inverse automatically when it can reliably infer it from your schema. For a single one-to-one or one-to-many pair it can; between two arrays it does not. Declaring it is the better habit. A reader sees the pairing without guessing, and the code keeps working when someone later adds a second relationship between the same two models, which makes inference impossible. Declare it on **one** side only: when both properties name each other in `@Relationship(inverse:)`, the two macros refer to each other and the build fails with a circular-reference error. ## One-to-one and the other shapes A user who may or may not have a profile is a **one-to-one** relationship: `User.profile: Profile?` and `Profile.user: User?`. Both sides are optional, and SwiftData infers the inverse exactly as it does for one-to-many. | Shape | One side | Other side | Inverse | |---|---|---|---| | One-to-one | `var profile: Profile?` | `var user: User?` | inferred, or declared once | | One-to-many | `var tasks: [ProjectTask] = []` | `var project: Project?` | inferred, or declared once | | Many-to-many | `var tags: [Tag] = []` | `var tasks: [ProjectTask] = []` | must be declared once | The many-to-many row is the exception worth remembering: SwiftData does not infer an inverse between two arrays, so without `inverse:` you get two unrelated one-way lists. ## What comes with the declaration - **Schema discovery.** `ModelContainer(for: Project.self)`, or the `modelContainer(for:)` modifier, needs only the root type. Apple's documentation says SwiftData traverses a model's relationships and includes the destination types for you. - **A default delete rule.** Without `deleteRule:` the rule is `.nullify`: deleting a project clears each task's `project` and keeps the tasks. Choosing `.cascade` is a separate decision about who owns whom. - **Optional to-many.** An array relationship may also be declared optional, `[ProjectTask]?`. A store synced with CloudKit needs every relationship optional. - **No join model.** You never declare a link table or a foreign-key property; SwiftData stores the link itself. ## Mistakes reviewers catch - Writing `@Relationship(inverse:)` on both properties "so each side knows the other". The compiler rejects it. - Making the back-reference non-optional (`var project: Project`) and then deleting a project with the default rule: SwiftData cannot set the task's reference to `nil`, and the save fails. - Keeping a separate `projectID` attribute next to the relationship and updating the two by hand, which lets them drift apart. - Listing every related type in the container "to be safe". It is harmless, but it hides the fact that the root type already brings its graph with it.

  • Do you need the @Relationship macro at all for this one-to-many link?
    No. A property whose type is a model or an array of models is already a relationship, and for a single one-to-many pair SwiftData infers the inverse. You add `@Relationship` to choose a delete rule, to name the inverse explicitly, to set `minimumModelCount` or `maximumModelCount`, or to record an `originalName` after a rename.
  • Why is the task's project property optional rather than non-optional?
    A task may be created before it is filed, and the default `.nullify` rule sets the back-reference to `nil` when its project is deleted. With `var project: Project` SwiftData has nowhere to put that `nil`, so the save that follows the delete fails. Make it optional, or cascade the delete so the tasks go with the project.
  • Can the to-many side be an optional array?
    Yes. SwiftData accepts `[ProjectTask]?` as well as `[ProjectTask]`. Code then has to unwrap it, but some setups need it: a store synced with CloudKit requires every relationship to be optional.

  • You must declare a join model or a projectID attribute to link two models.
  • Put @Relationship(inverse:) on both properties so each side knows the other.
  • The @Relationship macro is required on any property whose type is another model.
  • Every related model type must be listed in ModelContainer(for:) or it is not stored.
  • The other end of the link only updates after the context saves.