skip to content

Schema Migrations

A VersionedSchema plus a SchemaMigrationPlan describe how a store moves between shapes, lightweight where possible and custom where not. It decides whether a shipped model evolves without data loss.

on this pageshow

explore

questions

5

In SwiftData, which schema changes can a lightweight MigrationStage carry, and which ones need a custom stage?

level: middleimportance: should knowfreq 40%

answer

  1. shape edits vs value edits
  2. optional or defaulted additions
  3. a rename needs its old name
  4. values rewritten need your code

basics

~20 s

A lightweight SwiftData stage handles added attributes that are optional or have a default, removed attributes, and renames declared with @Attribute(originalName:). Changes that must read and rewrite stored values, such as splitting a field or converting a type, need a custom stage.

solid answer

~40 s

A `.lightweight(fromVersion:toVersion:)` stage lets SwiftData infer the move from the two schemas: added attributes that are optional or have a default value, removed attributes, and renames you declare with `@Attribute(originalName:)`. Adding `.unique` is lightweight too, as long as no stored rows collide. Anything that must read old values and compute new ones goes in `.custom(fromVersion:toVersion:willMigrate:didMigrate:)`: de-duplicating before a unique rule, splitting one field into two, or converting a value to a new type. In a Trip release that renames a date, splits a traveller name and adds a unique booking reference, only the rename is lightweight for certain. A rename without `originalName` is read as one attribute removed and another added, so the old values are silently lost.

go deeper

for a junior

Recall that adding an optional property, or renaming one with @Attribute(originalName:), migrates without extra code, while a forgotten originalName loses the old values.

for a middle

Explain the line: a lightweight stage infers shape changes from two schemas, while anything that must read and rewrite stored values needs a custom stage with willMigrate or didMigrate.

for a senior

Show that you check shipped data before relying on lightweight: duplicates break a new unique rule, an incompatible type fails the open, and a missing originalName drops data silently.

for a principal

Discuss keeping most changes lightweight, for example adding optional fields and backfilling later, so custom migration code stays rare, small and easy to review.

## What a migration stage is SwiftData describes each shipped shape of your models as a **`VersionedSchema`**, and a **`SchemaMigrationPlan`** lists those versions plus one **`MigrationStage`** for each step between them. `MigrationStage` is an enum with exactly two cases: - **`.lightweight(fromVersion:toVersion:)`**: you name the two versions and SwiftData works out the move by comparing them. You write no migration code. - **`.custom(fromVersion:toVersion:willMigrate:didMigrate:)`**: the same move, plus two optional closures that receive a `ModelContext` so your code can read, fix and save data around the schema change. The question is always the same: can the destination be derived from the source by looking at the two schemas alone, or does someone have to decide what each stored value becomes? ## What lightweight inference can do Lightweight inference matches entities and attributes by name and copies the values across. It handles changes where that matching is enough: | Change | Lightweight? | Why | |---|---|---| | Add an optional attribute (`var notes: String?`) | Yes | Existing rows get `nil` | | Add a non-optional attribute with a default (`var nights = 1`) | Yes | Existing rows get the default | | Add a non-optional attribute with no default | No | The store has no value to give existing rows | | Remove an attribute | Yes | Its column and values are dropped | | Rename with `@Attribute(originalName:)` | Yes | The old name tells SwiftData which column the new name continues | | Rename without `originalName` | Migrates, but loses data | Seen as one attribute removed and another added | | Add `.unique` when no rows collide | Yes | The constraint holds for existing data | | Add `.unique` when rows collide | No | The constraint fails during the migration | | Change an attribute's type, such as `String` to `Int` | No | Source and destination types are incompatible | When a lightweight step cannot be done, the migration fails and `ModelContainer`'s initializer throws instead of opening the store. ## What needs a custom stage A custom stage is for decisions that only your code can make: - **Splitting or merging fields**: deciding where a full name breaks into a first and last name. - **Converting values**: turning a free-text `"4"` into an `Int`, or a string into an enum's raw value. - **Cleaning data so a new rule can hold**: removing or merging duplicates before `@Attribute(.unique)` or `#Unique` is added. - **Backfilling a new attribute from other data**: computing a value instead of taking one default for every row. `willMigrate` runs while the store still has the source shape, and `didMigrate` runs after it has the destination shape. Which closure you use depends on whether you need the old attributes or the new ones. ## The Trip release, change by change Take a shipped app whose Trip model, in its third release, renames `startDate` to `departureDate`, splits `travelerName` into `firstName` and `lastName`, and makes `bookingReference` unique: 1. **The rename** is lightweight, as long as the new property carries `@Attribute(originalName: "startDate")`. 2. **The split** needs custom code: no inference can know where a name breaks. 3. **The unique rule** is lightweight only if no two stored trips share a reference. Shipped data rarely guarantees that, so plan for a custom stage that de-duplicates first. The lightweight parts of the new version look like this: ```swift enum TripSchemaV3: VersionedSchema { static let versionIdentifier = Schema.Version(3, 0, 0) static var models: [any PersistentModel.Type] { [Trip.self] } @Model final class Trip { @Attribute(originalName: "startDate") var departureDate = Date.now var notes: String? var nights = 1 init() {} } } ``` The default value `1` is what existing rows receive for `nights`, and `notes` starts as `nil`. ## Common traps - **Forgetting `originalName`.** Nothing throws: the migration succeeds and the renamed property comes back holding its default. The loss is silent. - **Assuming every change needs `.custom`.** Many changes are additive; keeping them lightweight keeps migration code small and reviewable. - **Assuming a unique rule is free.** Whether it migrates depends on the data in users' stores, not on the code. - **Changing a type in place.** Model it as a new attribute, copy and convert in a custom stage, and drop the old one in a later stage. - **Treating a clean simulator as proof.** A rule that depends on data, such as uniqueness, passes on fresh test data and fails on devices whose data predates it. Check the step against a store produced by the shipped build. The rule of thumb: if the change can be described by names alone, it is lightweight; if it needs a decision about values, it is custom.

  • What happens if you rename a SwiftData property without @Attribute(originalName:)?
    SwiftData compares the two schemas, sees one attribute that disappeared and one that is new, and migrates without complaint. The new property comes back holding its default value and the old values are dropped. Nothing throws, so the loss stays silent until a user notices. `originalName` is what tells SwiftData that the two names are the same data.
  • Can a lightweight SwiftData stage change a String attribute to an Int?
    No. Inference rejects source and destination attribute types that are incompatible, the migration fails and `ModelContainer`'s initializer throws. Model the conversion explicitly: add the new attribute in an intermediate version, convert the values in a custom stage, and drop the old attribute in a following lightweight stage.
  • Does adding a non-optional SwiftData attribute need a custom stage?
    Not if it has a default value: SwiftData takes the property's initial value as the attribute's default, and existing rows receive it during a lightweight migration. A non-optional attribute with no default fails, with a validation error about missing values on a mandatory attribute, so either give it a default or fill it in a custom stage.

  • Renaming a property is safe as long as its type stays the same.
  • A lightweight migration can split one field into two by itself.
  • Every schema change needs a custom stage with willMigrate and didMigrate.
  • Adding @Attribute(.unique) never needs migration code.
  • An added non-optional property with no default migrates because SwiftData fills in zero.
open as a page

In SwiftData, how do VersionedSchema and SchemaMigrationPlan fit together, and how does the plan reach the ModelContainer?

level: middleimportance: should knowfreq 38%

basics

~10 s

Each VersionedSchema freezes one shipped shape: a versionIdentifier and the @Model types nested in it. A SchemaMigrationPlan lists those schemas and the MigrationStage between each pair, and you pass it to ModelContainer(for:migrationPlan:configurations:).

open as a page

In SwiftData, a release adds @Attribute(.unique) to Trip.bookingReference, but shipped stores hold duplicates; why does the store fail to open, and how does a custom stage fix it?

level: seniorimportance: should knowfreq 25%

basics

~20 s

A lightweight stage applies the new unique constraint to rows that already collide, so the migration fails and ModelContainer's initializer throws. A custom stage's willMigrate fetches the old Trip type, keeps one trip per reference, removes or merges the rest and saves.

open as a page

For a SwiftData app about to ship its first release, would you declare a VersionedSchema and SchemaMigrationPlan from day one, or wait for the first change that needs them?

level: principalimportance: should knowfreq 30%

basics

~20 s

Both work: automatic migration covers additive changes without a plan, and a later plan can adopt an unversioned store if its first VersionedSchema matches the shipped models exactly. Day-one versioning records that shape while it is certain, at the cost of frozen types.

open as a page

In SwiftData, a single custom MigrationStage that splits Trip.travelerName into firstName and lastName ends with empty names; why, and what plan keeps the data?

level: seniorimportance: nice to knowfreq 18%

basics

~20 s

willMigrate runs while the store has the old shape, before firstName and lastName exist, and didMigrate runs after travelerName is already dropped. Add an intermediate version holding both fields, copy in its didMigrate, then drop travelerName in a lightweight stage.

open as a page