skip to content

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

level: middleimportance: should knowfreq 38%

answer

  1. one frozen snapshot per version
  2. models nested in each version
  3. schemas plus stages
  4. the container initializer, not the modifier

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:).

solid answer

~40 s

A `VersionedSchema` is usually an enum with a `versionIdentifier` such as `Schema.Version(2, 0, 0)` and a `static var models` list, with that version's `@Model` classes nested inside so `TripSchemaV1.Trip` and `TripSchemaV2.Trip` can coexist. The rest of the app uses the newest through a typealias. A `SchemaMigrationPlan` returns its `schemas`, oldest first, and its `stages`, one `MigrationStage` per step. You pass the plan to `ModelContainer(for:migrationPlan:configurations:)`. The SwiftUI `modelContainer(for:)` modifiers take no plan, so you build the container yourself and install it with `.modelContainer(container)`. When the container opens a store, it matches the store to one of the plan's versions and runs the stages from there to the current one.

code

swift · 36 lines
swift
import Foundation
import SwiftData

enum TripSchemaV1: VersionedSchema {
    static let versionIdentifier = Schema.Version(1, 0, 0)
    static var models: [any PersistentModel.Type] { [Trip.self] }
    @Model final class Trip {
        var name = ""
        var startDate = Date.now
        init() {}
    }
}

enum TripSchemaV2: VersionedSchema {
    static let versionIdentifier = Schema.Version(2, 0, 0)
    static var models: [any PersistentModel.Type] { [Trip.self] }
    @Model final class Trip {
        var name = ""
        var startDate = Date.now
        var notes: String?          // added: optional, so lightweight
        init() {}
    }
}

typealias Trip = TripSchemaV2.Trip  // the app's code uses the newest version

enum TripMigrationPlan: SchemaMigrationPlan {
    static var schemas: [any VersionedSchema.Type] { [TripSchemaV1.self, TripSchemaV2.self] }
    static var stages: [MigrationStage] {
        [.lightweight(fromVersion: TripSchemaV1.self, toVersion: TripSchemaV2.self)]
    }
}

func makeTripContainer() throws -> ModelContainer {
    try ModelContainer(for: Trip.self, migrationPlan: TripMigrationPlan.self)
}

go deeper

for a junior

Recall the three names: VersionedSchema for one version, SchemaMigrationPlan for the list, MigrationStage for each step, and that the plan goes to ModelContainer.

for a middle

Explain why model classes are nested per version, what schemas and stages each return, and why an app with a plan builds its ModelContainer instead of using the modelContainer(for:) modifier.

for a senior

Show the production habits: shipped versions are frozen, migration code names frozen types, and the container's initializer error is caught and handled rather than force-tried.

for a principal

Weigh where the container is created and who owns the plan file, so every model change in review visibly adds a version and a stage.

## The three pieces SwiftData's migration API is three declarations, all available since iOS 17: | Piece | Kind | What it holds | |---|---|---| | `VersionedSchema` | protocol | `versionIdentifier` (a `Schema.Version`) and `models`, the `@Model` types of one version | | `SchemaMigrationPlan` | protocol | `schemas`, every version the app knows, and `stages`, the moves between them | | `MigrationStage` | enum | `.lightweight(fromVersion:toVersion:)` or `.custom(fromVersion:toVersion:willMigrate:didMigrate:)` | A **versioned schema** is a frozen photograph of your models as one release shipped them. The **plan** is the route between photographs. The **container** is what reads a user's store, works out which photograph it matches and walks the route. ## Declaring a versioned schema The usual shape is an enum per version: - `static let versionIdentifier = Schema.Version(1, 0, 0)`. `Schema.Version` takes major, minor and patch numbers; give every version its own. - `static var models: [any PersistentModel.Type]` lists the model types of that version. - The `@Model` classes are **nested** in the enum. Two top-level classes cannot both be called `Trip`, but `TripSchemaV1.Trip` and `TripSchemaV2.Trip` can, and both still describe the entity `Trip` in the store. - The app's own code uses `typealias Trip = TripSchemaV2.Trip`, so only migration code ever names an old version. Once a version has shipped, its nested types are **frozen**. A change to a model is a new version, never an edit to an old one, because the old types are the only description SwiftData has of stores still at that version. ## Writing the plan A plan is usually another enum conforming to `SchemaMigrationPlan`: 1. `schemas` returns every version, oldest first: `[TripSchemaV1.self, TripSchemaV2.self]`. 2. `stages` returns one `MigrationStage` per step, naming the versions on each side. 3. Each stage is `.lightweight` when SwiftData can infer the change, or `.custom` when your code must read or fix data in `willMigrate` or `didMigrate`. 4. When a release adds a version, append it to `schemas` and append a stage; the earlier entries stay as they are. A user who skipped releases is handled by the same list: the container starts from the store's version and runs each later stage in order. ## Passing the plan to the container The plan does nothing until a container knows about it. `ModelContainer` has initializers that take it, such as `ModelContainer(for:migrationPlan:configurations:)`, where `migrationPlan` defaults to `nil`. Two details catch teams out: - The SwiftUI modifier `modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)` has **no migration plan parameter**. An app that needs a plan creates the `ModelContainer` itself, usually as a property of the `App`, handles the error the initializer can throw, and installs it with `modelContainer(_:)`. - Document-based apps have their own route: `DocumentGroup(editing:migrationPlan:editor:prepareDocument:)` takes the plan directly. Apple's `ModelContainer` documentation also says the container migrates automatically as the schema evolves, and that a plan is how you take part when the changes exceed what automatic migration can do. An app with only additive changes can run without a plan; the plan becomes necessary when a step needs a custom stage, and useful earlier as a record of what shipped. ## How the container uses the plan When the container opens a store, the plan decides what happens: - **A new install** has no store yet, so the container creates one directly in the current shape; no stage runs. - **A store already at the current version** opens with nothing to do. - **A store at an older version** is matched to one of the plan's `schemas`, and the container runs each stage from that version up to the current one, in the same open. - **A store that matches none of them** cannot be migrated, and the initializer throws. The stages run while the initializer is opening the store, so a custom stage's work happens before the app receives its container. A container can also be built from a schema value, `Schema(versionedSchema: TripSchemaV2.self)`, which reads the models and version from the versioned schema; the same plan argument applies. ## What goes wrong - **Editing a shipped version in place.** Stores already at that version no longer match its description, and the container's initializer throws. - **A version missing from `schemas`.** A store at that version matches nothing the container knows. - **Migration code using the typealias.** It changes meaning in the next release; name the frozen types (`TripSchemaV1.Trip`) instead. - **A `try!` on the container.** A failed migration then crashes at launch with no chance to report it; catch the error and decide what the app shows. The code example declares two versions, a plan with one lightweight stage, and a function that builds the container with the plan, ready to hand to `modelContainer(_:)`.

  • Why are the @Model classes nested inside each SwiftData VersionedSchema enum?
    Each version needs its own Swift type with the exact shape that shipped, and two top-level classes cannot share the name `Trip`. Nesting gives `TripSchemaV1.Trip` and `TripSchemaV2.Trip` distinct Swift names while both describe the same `Trip` entity in the store. The app uses a typealias to the newest, so only migration code names the old ones.
  • Can the SwiftUI modelContainer modifier take a SchemaMigrationPlan?
    No. `modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)` takes model types and switches but no plan. Create the container with `ModelContainer(for:migrationPlan:configurations:)` in the `App`, handle the error it can throw, and install it with `modelContainer(_:)`. Document-based apps use the `DocumentGroup` initializer that takes `migrationPlan`.
  • Does SwiftData migrate a store when the app has no SchemaMigrationPlan at all?
    Yes, for changes it can infer. Apple's `ModelContainer` documentation says the container migrates automatically as the schema evolves, and a plan lets you take part when changes go beyond that. Adding an optional property to an unversioned model opens fine without a plan; a split field or a unique rule over duplicates needs one.

  • The SwiftUI modelContainer(for:) modifier accepts a migrationPlan argument.
  • One Trip class can serve every schema version if you edit it in place.
  • SwiftData needs a migration plan for any change, even a new optional property.
  • Migration stages should use the app's current typealias rather than the frozen types.