skip to content

In SwiftData, what do @Relationship's delete rules do, and why does deleting a Project leave its Tasks behind by default?

level: middleimportance: must knowfreq 60%

answer

  1. four cases on one enum
  2. the default clears references
  3. orphans versus owned children
  4. rule sits on the deleted side

basics

~20 s

A delete rule says what happens to related models when a model is deleted. The default, .nullify, only clears the tasks' project reference, so the tasks survive as orphans; .cascade on Project.tasks deletes them with the project.

solid answer

~40 s

`@Relationship(deleteRule:)` takes a `Schema.Relationship.DeleteRule`: `.nullify` (the default), `.cascade`, `.deny` or `.noAction`. The rule belongs to the property on the model being deleted. With `.nullify` on `Project.tasks`, deleting a project sets each task's `project` to `nil` and keeps the tasks, which is why they remain as orphans. `@Relationship(deleteRule: .cascade, inverse: \ProjectTask.project)` deletes them with the project, and a batch `delete(model:where:)` honours the cascade too. `.deny` is meant to refuse the delete while tasks remain, and `.noAction` leaves the related models' cleanup to you. Two traps: a non-optional back-reference cannot be nullified, so that save throws; and the rule needs its `deleteRule:` label, because the unlabeled argument is a `Schema.Relationship.Option`.

code

swift · 24 lines
swift
import SwiftData

@Model
final class Project {
    var name: String
    // Deleting a project deletes its tasks too.
    @Relationship(deleteRule: .cascade, inverse: \ProjectTask.project)
    var tasks: [ProjectTask] = []

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

@Model
final class ProjectTask {
    var title: String
    var project: Project?

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

func remove(_ project: Project, from context: ModelContext) throws {
    context.delete(project)   // its tasks are deleted with it
    try context.save()
}

go deeper

for a junior

Know the default rule is nullify, that it leaves the children in place, and that cascade deletes them along with the parent.

for a middle

Explain which property carries the rule, what each of the four cases does, and why the non-optional back-reference fails at save.

for a senior

Show you test delete behaviour rather than trusting it: deny needs a code guard, batch deletes behave differently, and orphans need a query or a migration to clean up.

for a principal

Set a team rule for ownership: every to-many relationship states its delete rule explicitly in review, so orphans are a decision rather than a default.

## What a delete rule decides When you call `context.delete(project)`, the project's tasks still exist, and something has to happen to the links between them. A **delete rule** is that decision, set per relationship with the `deleteRule:` argument of `@Relationship`. Its type is `Schema.Relationship.DeleteRule`, an enum with four cases, and the default is `.nullify`. The rule is attached to the property **on the model being deleted**. `Project.tasks` decides what deleting a project does to its tasks; `ProjectTask.project` decides what deleting a task does to its project. That second relationship keeps the default, which is why deleting one task just removes it from its project's array. | Rule | Deleting a `Project` with tasks | Typical use | |---|---|---| | `.nullify` (default) | each task's `project` becomes `nil`; the tasks stay | related data that outlives the parent | | `.cascade` | the tasks are deleted too | children owned by the parent | | `.deny` | intended to refuse the delete while tasks remain | parents that must be emptied first | | `.noAction` | SwiftData changes nothing on the tasks | cleanup you manage yourself | Apple describes `.cascade` as "a rule that deletes any related models" and `.nullify` as "a rule that nullifies the related model's reference to the deleted model". ## Why the tasks survive by default With no `deleteRule:`, `Project.tasks` is `.nullify`. Deleting a project and saving leaves every task in the store with `project == nil`. Those are **orphans**: they no longer appear under any project, yet they still exist, and any query over all tasks finds them. For a project-management app that is usually wrong, because tasks belong to their project, so the owning side declares the cascade: 1. Decide which side owns the other. Here the project owns its tasks. 2. Put `.cascade` on the owner's to-many property, `Project.tasks`. 3. Leave the child's back-reference, `ProjectTask.project`, at the default, so deleting a task never deletes its project. Cascade runs in more than one call. `context.delete(project)` removes the project's tasks with it, and Apple's sample shows that `context.delete(model: AnimalCategory.self)`, the batch form `delete(model:where:includeSubclasses:)`, also deletes the animals of every deleted category through the cascade rule. ## The rarer rules and their traps - **`.deny`** carries Core Data's meaning: a model that still has related models should not be deletable. Apple's documentation does not say how a refused delete is reported, and in a test on macOS 27 a single `context.delete(project)` followed by `save()` went through anyway, leaving the tasks with a `nil` project. Guard the delete in code, for example by checking `project.tasks.isEmpty`, and cover it with a test before you rely on the rule. A batch `delete(model:where:)` on a model with a `.deny` relationship throws a Core Data error saying the delete rule is not supported for batch deletes. CloudKit-synced stores cannot use `.deny` at all. - **`.noAction`** tells SwiftData not to touch the related models. Keeping the graph consistent afterwards is your job, so it is rarely the right choice. - **A non-optional back-reference.** If the task declares `var project: Project` and the project's relationship nullifies, SwiftData has no `nil` to write. The delete itself is accepted, and the next `save()` throws a `SwiftDataError`. Make the reference optional or cascade. - **The label.** `@Relationship(.cascade)` does not compile. The first, unlabeled parameter is a variadic list of `Schema.Relationship.Option`, whose only value is `.unique`; the rule must be written `deleteRule: .cascade`. ## When the effects become final A delete, like any change, is pending in the context until it is saved, by autosave or by an explicit `save()`. A nullified reference can still read the old project until that save, so read the result after saving, not just after `delete(_:)`, and test delete behaviour with `autosaveEnabled` turned off and an explicit `try context.save()`. ## Choosing in review - Owned children, such as a project's tasks or a trip's bookings: `.cascade`. - Shared or independent data, such as tags used by many tasks: keep `.nullify`. - "Must be empty first": `.deny` plus a code-level check, with the user told why the delete is blocked. - Anything with `.noAction`: ask who cleans up, and where. A focused test settles any doubt about a rule: create an in-memory container, turn `autosaveEnabled` off, insert a project with two tasks, delete the project, call `try context.save()`, then check `fetchCount` for the tasks. Zero means the cascade ran; two means the tasks are orphans.

  • Which side of a one-to-many link should carry .cascade?
    The side whose deletion should propagate: the owner's to-many property, `Project.tasks`. The rule applies when the model holding that property is deleted. Putting `.cascade` on `ProjectTask.project` instead would make deleting a single task delete its whole project, leaving that project's other tasks behind as orphans.
  • What happens if the task's project property is non-optional and the project's rule is the default?
    The default `.nullify` has to set each task's `project` to `nil`, which a non-optional property cannot hold. The delete is accepted in the context, and the following `save()` throws a `SwiftDataError`. Either make the reference optional so orphans are allowed, or cascade so no task outlives its project.
  • Does a batch delete with delete(model:where:) apply delete rules?
    It applies `.cascade`: Apple's sample deletes every category and SwiftData deletes their animals through the cascade rule. A model with a `.deny` relationship is different: the batch call throws a Core Data error saying the delete rule is not supported for batch deletes.

  • Deleting a parent always deletes its children in SwiftData.
  • To delete a project's tasks with it, put .cascade on ProjectTask.project.
  • @Relationship(.cascade) is the short form of deleteRule: .cascade.
  • Orphaned tasks are cleaned up by SwiftData at the next launch.
  • A non-optional back-reference is safe with the default delete rule.