Pocket How
Data and architecture

SwiftData schema migrations: VersionedSchema, migration plans and the traps

iOS 17+, iPadOS 17+. Advanced. By Cihat Salik, .

Short answer

Wrap every shipped model set in its own VersionedSchema, list them in order in a SchemaMigrationPlan, and add a lightweight stage for inferable changes or a custom stage when data must be cleaned or derived. Never edit a schema that has shipped, copy every model into each version, and test the upgrade from a real store made by the previous build.

The problem

You add a property to a SwiftData model, ship the update, and some users open the app to a crash in the ModelContainer initializer. Or worse, the app opens with an empty store. SwiftData migrates many changes on its own, so it is easy to skip versioning until the day a change needs it, and by then the shipped store has no version to migrate from. The fix is cheap if you set it up before your first release and keep a few rules.

All APIs here are iOS 17 unless noted.

Version from the first release

A VersionedSchema describes the exact set of models one release of your app shipped. A SchemaMigrationPlan lists those versions in order and the stages between them. Donny Wals puts the rule plainly in his deep dive on SwiftData migrations: every data model should have at least one versioned schema, even before anything changes.

Nest each version’s models inside an enum so each version owns its own types:

import Foundation
import SwiftData

enum NotesSchemaV1: VersionedSchema {
    static let versionIdentifier = Schema.Version(1, 0, 0)
    static var models: [any PersistentModel.Type] { [Note.self, Folder.self] }

    @Model
    final class Folder {
        var name: String = ""
        @Relationship(deleteRule: .cascade, inverse: \Note.folder)
        var notes: [Note] = []
        init(name: String) { self.name = name }
    }

    @Model
    final class Note {
        var title: String = ""
        var body: String = ""
        var folder: Folder?
        init(title: String, body: String) {
            self.title = title
            self.body = body
        }
    }
}

typealias Note = NotesSchemaV1.Note
typealias Folder = NotesSchemaV1.Folder

The typealiases let the rest of the app say Note and Folder. When a new version ships, you move them to point at the new version and nothing else in the app changes. Donny Wals presents this as a convenience, and it is the one that keeps version churn out of your views.

In Swift 6 language mode, declare versionIdentifier as static let or a computed static var. A stored static var is global mutable state and fails strict concurrency checking.

Add a version per release, not per edit

Create a new VersionedSchema when you change models after a version has shipped. While you are still developing a release, keep editing the unreleased version. Wals ties this to app updates: one new schema version per update that changes the model, at most.

Version 2 adds a pinned flag and makes titles unique:

enum NotesSchemaV2: VersionedSchema {
    static let versionIdentifier = Schema.Version(2, 0, 0)
    static var models: [any PersistentModel.Type] { [Note.self, Folder.self] }

    @Model
    final class Folder {
        var name: String = ""
        @Relationship(deleteRule: .cascade, inverse: \Note.folder)
        var notes: [Note] = []
        init(name: String) { self.name = name }
    }

    @Model
    final class Note {
        @Attribute(.unique) var title: String = ""
        var body: String = ""
        var isPinned: Bool = false
        var folder: Folder?
        init(title: String, body: String) {
            self.title = title
            self.body = body
        }
    }
}

Folder did not change, and it is still copied into V2. That is deliberate, and the reason is in the traps section below.

Choose lightweight or custom stages

A lightweight stage needs no code. SwiftData infers the mapping. Paul Hudson’s lightweight vs complex migrations chapter lists what qualifies: adding models, adding properties with defaults, renaming or deleting properties, toggling .externalStorage or .allowsCloudEncryption, changing delete rules, and adding .unique when the existing values are already unique.

A custom stage is needed when existing data has to change: deduplicating before a unique constraint, filling a new required value from old data, splitting or merging entities, or changing a property’s type.

MigrationStage.custom(fromVersion:toVersion:willMigrate:didMigrate:) gives you two closures, each with a ModelContext:

  • willMigrate runs against the old schema before the change. Use it to clean data so the new schema can be applied.
  • didMigrate runs against the new schema after the change. Use it to fill new properties from what is already there.

Both closures are @Sendable and take only the context, so they cannot share mutable state with each other. Design stages so each closure can do its work from what is in the store.

V1 to V2 needs a custom stage, because users may already have two notes with the same title. Apple’s WWDC23 session Model your schema with SwiftData uses the same case: deduplicate in willMigrate.

enum NotesMigrationPlan: SchemaMigrationPlan {
    static var schemas: [any VersionedSchema.Type] {
        [NotesSchemaV1.self, NotesSchemaV2.self, NotesSchemaV3.self]
    }

    static var stages: [MigrationStage] { [v1ToV2, v2ToV3] }

    static let v1ToV2 = MigrationStage.custom(
        fromVersion: NotesSchemaV1.self,
        toVersion: NotesSchemaV2.self,
        willMigrate: { context in
            let notes = try context.fetch(FetchDescriptor<NotesSchemaV1.Note>())
            let groups = Dictionary(grouping: notes, by: \.title)
            for (title, duplicates) in groups where duplicates.count > 1 {
                for (offset, note) in duplicates.dropFirst().enumerated() {
                    note.title = "\(title) (\(offset + 2))"
                }
            }
            try context.save()
        },
        didMigrate: nil
    )

    static let v2ToV3 = MigrationStage.lightweight(
        fromVersion: NotesSchemaV2.self,
        toVersion: NotesSchemaV3.self
    )
}

The dedup renames rather than deletes. Throwing away a user’s note to satisfy a constraint is the kind of migration bug nobody forgives. Use try, never try?, inside stages. A swallowed error turns a clear migration failure into a mysterious launch crash later.

V3 is a rename, which stays lightweight if you map the old name with originalName:

enum NotesSchemaV3: VersionedSchema {
    static let versionIdentifier = Schema.Version(3, 0, 0)
    static var models: [any PersistentModel.Type] { [Note.self, Folder.self] }

    @Model
    final class Folder {
        var name: String = ""
        @Relationship(deleteRule: .cascade, inverse: \Note.folder)
        var notes: [Note] = []
        init(name: String) { self.name = name }
    }

    @Model
    final class Note {
        @Attribute(.unique) var title: String = ""
        @Attribute(originalName: "body") var content: String = ""
        var isPinned: Bool = false
        var folder: Folder?
        init(title: String, content: String) {
            self.title = title
            self.content = content
        }
    }
}

Without originalName, SwiftData sees a deleted body and a new content, and the text is gone.

Finally, build the container from the current schema and the plan:

func makeContainer() throws -> ModelContainer {
    try ModelContainer(
        for: Schema(versionedSchema: NotesSchemaV3.self),
        migrationPlan: NotesMigrationPlan.self,
        configurations: ModelConfiguration()
    )
}

SwiftData reads the store’s version, then runs every stage from there to V3 in order. A user on V1 gets both stages.

When a new required value needs data

Adding a non-optional property with no sensible default is where most “simple” migrations fail. Wals points out that a default in the Swift initializer does not necessarily backfill existing rows. The pattern that works is a bridge:

  1. In version N, add the new property as optional. That stage is lightweight.
  2. In the same stage’s didMigrate, or in a custom stage, fill it from existing data.
  3. In version N+1, once every row has a value, tighten the type if you need to.

It costs an extra schema version and saves you from a store that cannot open.

Traps that crash or lose data

Editing a schema that already shipped. If you change NotesSchemaV1 after release, it no longer describes the stores on users’ devices, and the migration plan has no version that does. Treat shipped versions as frozen files, and put every change in a new version.

Sharing a model between versions. In the Apple Developer Forums thread SwiftData ‘simple’ migration failing, a developer’s lightweight migration crashed the container with an error saying staged migration cannot use an unknown model version. Some models were defined once and listed in both versions while the models they related to changed. Apple DTS’s fix was to give every version its own copy of every model, including the unchanged ones. That is why Folder appears in V1, V2 and V3 above.

A non-optional property without a default. Existing rows have no value for it. The same thread shows the related error about missing values on a mandatory attribute. Add a default or make it optional, then use the bridge pattern.

Adding .unique over duplicate data. Hudson notes the lightweight migration fails and the container does not load. Deduplicate in willMigrate first.

Forgetting a version in schemas. The plan needs every shipped version in order, and a stage for each adjacent pair. A missing middle version leaves users on it stranded.

Synced stores. If the store syncs with CloudKit, the CloudKit schema is additive only once promoted to Production. Renames and deletes that are fine locally are not fine there. Design synced models to only grow.

Shipping without any versioned schema. Apps that launched unversioned and add versioning later report trouble on the forums. If you are there, make your first VersionedSchema match the shipped models exactly, property for property, and test it against a store from the App Store build.

Test migrations by hand

Unit tests that create a fresh store prove nothing about migration, because a fresh store has nothing to migrate. Wals’ advice is to test from older builds with messy, real data. A manual routine that catches nearly everything:

  1. Check out the tag of the last release and run it in a simulator.
  2. Create realistic data, including the awkward cases: duplicate titles, empty strings, very long text, missing relationships.
  3. Copy the store out so you can repeat the test. Find the app’s data folder with:
xcrun simctl get_app_container booted com.example.notes data

The default store is default.store under Library/Application Support, with its -shm and -wal files beside it. Copy all three. 4. Install the new build over the old one without deleting the app, and launch. 5. Check the data, not just the launch. Count rows, open edited records, confirm renamed properties kept their values. 6. To repeat, restore the three files and launch again.

For a faster loop during development, point a ModelConfiguration(url:) at a copy of an old store bundled in a debug target, and open it with the migration plan. Keep a folder of stores from every shipped version and run each one through the current plan before every release.

Checklist

Change Stage Notes
Add model Lightweight Copy all models into the new version
Add optional property or one with a default Lightweight Defaults may not backfill; verify
Add required property from existing data Custom, didMigrate Use the optional-then-tighten bridge
Rename property Lightweight @Attribute(originalName:) or data is lost
Delete property Lightweight Never on a synced Production schema
Add .unique Custom, willMigrate Deduplicate first, rename instead of delete
Change a property’s type Custom Add new property, copy, remove old in a later version
Any change after release New VersionedSchema Never edit a shipped one

Keep the old schema enums in the project forever. They are small, and they are the only record of what is sitting in your users’ stores.

Sources and further reading

Read next