skip to content

In SwiftData, how do you model Tasks that share many Tags, and what happens to a shared Tag when one Task is deleted?

level: middleimportance: should knowfreq 45%

answer

  1. arrays on both sides
  2. not inferred between two arrays
  3. unlink by editing the array
  4. cascade reaches shared models

basics

~20 s

Give each model an array of the other and declare @Relationship(inverse:) on one side, because SwiftData does not infer a many-to-many inverse. With the default .nullify rule, deleting a task only removes its links, and the shared tag survives.

solid answer

~40 s

Many-to-many in SwiftData is two arrays, `ProjectTask.tags: [Tag]` and `Tag.tasks: [ProjectTask]`, paired with `@Relationship(inverse: \Tag.tasks)` on one of them. The inverse is not optional in practice: between two arrays SwiftData infers nothing, so without it you get two unrelated one-way lists and appending a tag never shows up in `tag.tasks`. You never declare a join model; SwiftData stores the links. To untag, remove the tag from `task.tags`, which updates both sides and deletes neither model. With the default `.nullify`, deleting a task drops its links and deleting a tag removes it from every task. `.cascade` on `ProjectTask.tags` is the trap: deleting one task then deletes each of its tags, including tags that other tasks still use.

code

swift · 22 lines
swift
import SwiftData

@Model
final class ProjectTask {
    var title: String
    @Relationship(inverse: \Tag.tasks)   // required: many-to-many is not inferred
    var tags: [Tag] = []

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

@Model
final class Tag {
    var name: String
    var tasks: [ProjectTask] = []

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

func untag(_ task: ProjectTask, from tag: Tag) {
    task.tags.removeAll { $0 == tag }   // unlinks both sides; deletes neither model
}

go deeper

for a junior

Remember the shape: an array on each model, and an inverse declared on one of them.

for a middle

Explain why the inverse is required between two arrays, how unlinking differs from deleting, and what the default rule does on each side.

for a senior

Spot the cascade on shared data in review and replace it with an explicit clean-up of unused tags, backed by a test with two tasks sharing a tag.

for a principal

Decide whether tags are shared vocabulary or per-task labels before the schema ships; that choice sets the relationship shape and the delete rules.

## The shape A **many-to-many** relationship links models where each side can have many of the other: a task carries several tags, and a tag such as "urgent" sits on many tasks. In SwiftData it is two to-many properties, one array on each model: - `ProjectTask.tags: [Tag]`, defaulting to `[]` - `Tag.tasks: [ProjectTask]`, defaulting to `[]` There is no join model to declare and no pair of identifiers to maintain. SwiftData stores the links between the two kinds of model itself. Either array may also be optional (`[Tag]?`), which a CloudKit-synced store requires. ## Why the inverse must be declared For a one-to-one or one-to-many pair, SwiftData can infer that two properties are each other's inverse. Between **two arrays** it does not. Leave out `inverse:` and the schema ends up with two independent one-way relationships: `task.tags.append(urgent)` succeeds, yet `urgent.tasks` stays empty, and the store keeps two separate sets of links that can disagree. The fix is one argument on one side: 1. Choose either property; the code example puts it on `ProjectTask.tags`. 2. Write `@Relationship(inverse: \Tag.tasks)` above it. 3. Leave `Tag.tasks` as a plain array. Naming the inverse on both sides makes the macros refer to each other, and the build fails. With the inverse in place, an edit on either side is reflected on the other immediately. ## Linking and unlinking | You want to | Do this | Effect | |---|---|---| | Tag a task | `task.tags.append(tag)` | `tag.tasks` gains the task | | Untag a task | remove the tag from `task.tags` | both sides drop the link; both models stay | | Delete a tag everywhere | `context.delete(tag)` | the tag is removed from every task's `tags` | | Delete a task | `context.delete(task)` | its links go; shared tags stay with the default rule | The most common bug in review is "untag" written as `context.delete(tag)`, which removes the tag from every other task as well. Removing the element from the array is the unlink operation. ## Delete rules on a many-to-many Both arrays default to `.nullify`, and for shared data that is the right rule: - Deleting a task clears its links. Every tag survives, including tags no other task uses. - Deleting a tag clears its links. Every task survives without it. `.cascade` is where shared data gets lost. With `@Relationship(deleteRule: .cascade, inverse: \Tag.tasks) var tags: [Tag]`, deleting one task deletes **each of its tags**, and those tags disappear from every other task that carried them. SwiftData does not count how many other tasks still reference a tag before cascading; the rule simply follows the links of the model being deleted. If unused tags should go away, that is a separate clean-up step: after deleting tasks, find tags whose `tasks` array is empty and delete those, in code you can test. ## Checking it - Write the relationship test with two tasks sharing one tag; delete one task and assert the other still has the tag. - Assert the inverse: after `task.tags.append(tag)`, `tag.tasks` contains the task. - Delete a tag and assert that every task which carried it no longer lists it, while the tasks themselves are still in the store. - Turn autosave off in tests and call `try context.save()` explicitly, so you check the saved state rather than pending changes. ## Checking what SwiftData stored When a tag screen and a task screen disagree, look at the schema the container actually built rather than at the model source. `container.schema.entitiesByName["ProjectTask"]?.relationshipsByName["tags"]?.inverseName` returns `"tasks"` when the pairing is in place and `nil` when SwiftData stored two one-way relationships. A one-line assertion of that value in a unit test keeps the pairing from being lost in a later refactor, for example when someone renames `Tag.tasks` and forgets the key path. Two unpaired arrays also explain a subtler symptom: data written from the task editor and data written from the tag editor each look complete on their own screen, because each screen reads the array it wrote. ## Reading the two arrays The arrays are not ordered by anything you can rely on after the models are reloaded from the store, so display tags sorted by a stored field such as `name`, not in the order they were appended.

  • What exactly goes wrong if you leave out inverse: on a many-to-many?
    SwiftData infers no inverse between two arrays, so it stores two independent one-way relationships. Appending a tag to `task.tags` leaves `tag.tasks` unchanged, and the two lists can disagree. Nothing fails at compile time or when the container opens, which is why it surfaces later as a tag screen that shows no tasks.
  • How would you delete tags that no task uses any more?
    Not with a cascade rule, which would also delete tags still in use. After deleting tasks, fetch the tags whose `tasks` array is empty and delete those explicitly, then save. Keep it in one function with a unit test so the rule is visible and checked.

  • Many-to-many needs a join model such as TaskTag with two to-one properties.
  • SwiftData infers the inverse between two arrays just as it does for one-to-many.
  • Cascade on a many-to-many only deletes tags no other task still uses.
  • To untag a task you delete the Tag model through the context.
  • Declare @Relationship(inverse:) on both arrays so each side updates the other.