Migrate SwiftData Values With An Intermediate Schema
A work planner used to store estimated durations in whole minutes. Now it needs seconds. Changing durationMinutes to durationSeconds is easy. Explaining to an existing database that 25 now means 1,500 takes a little more care.
A successful launch on an empty simulator proves surprisingly little here. Fresh installs are excellent at forgiving our migration mistakes.
We’ll build a small, local SwiftData migration that preserves the record’s ID and title, converts the duration, and stops if an old value cannot be represented safely. The useful trick is an intermediate schema where both properties exist at once.
These are established SwiftData APIs, available since iOS 17/macOS 14. The examples use explicit type-level nonisolated declarations and were checked with Xcode 27 / Swift 6.4. There is no new October API requirement.
Change the meaning, not just the name
@Attribute(originalName:) is useful when a property gets a new name but keeps its data. It does not perform our minutes-to-seconds calculation. Apple’s schema modeling session makes that distinction between schema mapping and custom migration work.
There is another trap: the two closures in a custom migration operate on different schema versions. willMigrate works with the source models; didMigrate works with the destination models. Neither is a general-purpose context containing every historical model.
Roman Mirzoyan’s migration write-up and an existing Stack Overflow discussion highlight that boundary. The question already has an answer. For this example, we can keep the conversion inputs in the store itself by introducing one extra schema.
| Schema | Stored duration properties | Purpose |
|---|---|---|
| V1 | durationMinutes | The old app’s data |
| V2 | durationMinutes and durationSeconds | A temporary place to perform the conversion |
| V3 | durationSeconds | The current app’s data |
The path is V1 → V2 → V3. V2 is a migration step; it does not need its own App Store release. These schema version numbers are separate from the app’s marketing version and build number.
Keep each schema’s definition
Put the following five Swift blocks in one file. Start with an exact description of the old model:
import Foundation
import SwiftData
nonisolated enum WorkSchemaV1: VersionedSchema {
static var versionIdentifier: Schema.Version { .init(1, 0, 0) }
static var models: [any PersistentModel.Type] { [WorkItem.self] }
@Model nonisolated final class WorkItem {
var id: UUID
var title: String
var durationMinutes: Int
init(id: UUID, title: String, durationMinutes: Int) {
self.id = id
self.title = title
self.durationMinutes = durationMinutes
}
}
}
Keep released definitions intact. Editing V1 to describe today’s model defeats the point of giving SwiftData a history to migrate from. In a larger app, each version’s models array must describe its complete schema, including the models involved in relationships. This deliberately small example has one model and no relationships.
The intermediate version adds a property with a simple stored default:
nonisolated enum WorkSchemaV2: VersionedSchema {
static var versionIdentifier: Schema.Version { .init(2, 0, 0) }
static var models: [any PersistentModel.Type] { [WorkItem.self] }
@Model nonisolated final class WorkItem {
var id: UUID
var title: String
var durationMinutes: Int
var durationSeconds: Int = 0
init(id: UUID, title: String, durationMinutes: Int) {
self.id = id
self.title = title
self.durationMinutes = durationMinutes
}
}
}
The declaration’s 0 lets this added scalar property have a value during the lightweight transition. It is a placeholder, not the conversion result. V2 is internal to the migration: the normal app must never open it and treat those seconds as authoritative.
V3 removes the old property. The current app supplies seconds when creating a record:
nonisolated enum WorkSchemaV3: VersionedSchema {
static var versionIdentifier: Schema.Version { .init(3, 0, 0) }
static var models: [any PersistentModel.Type] { [WorkItem.self] }
@Model nonisolated final class WorkItem {
var id: UUID
var title: String
var durationSeconds: Int = 0
init(id: UUID, title: String, durationSeconds: Int) {
self.id = id
self.title = title
self.durationSeconds = durationSeconds
}
}
}
typealias WorkItem = WorkSchemaV3.WorkItem
Each version keeps the same model name, WorkItem, and the unchanged properties. We update existing records during migration; we don’t delete them and insert replacements. The test fixtures check that application-level UUIDs and titles survive.
The explicit nonisolated declarations also let the migration code compile in a project whose default isolation is MainActor. They do not make a ModelContext or its fetched model instances safe to pass between unrelated tasks. Keep them within the migration callback’s execution.
Convert while both properties exist
The migration plan first expands V1 into V2. It then performs the conversion in V2’s context, before the transition to V3 removes the old field:
nonisolated enum DurationMigrationError: Error {
case invalidMinutes(UUID)
}
nonisolated func seconds(from minutes: Int, id: UUID) throws -> Int {
let result = minutes.multipliedReportingOverflow(by: 60)
guard minutes >= 0, !result.overflow else {
throw DurationMigrationError.invalidMinutes(id)
}
return result.partialValue
}
nonisolated enum WorkMigrationPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[WorkSchemaV1.self, WorkSchemaV2.self, WorkSchemaV3.self]
}
static var stages: [MigrationStage] {
[
.lightweight(
fromVersion: WorkSchemaV1.self,
toVersion: WorkSchemaV2.self
),
.custom(
fromVersion: WorkSchemaV2.self,
toVersion: WorkSchemaV3.self,
willMigrate: { context in
let rows = try context.fetch(
FetchDescriptor<WorkSchemaV2.WorkItem>()
)
let converted = try rows.map {
try seconds(from: $0.durationMinutes, id: $0.id)
}
for (row, value) in zip(rows, converted) {
row.durationSeconds = value
}
try context.save()
},
didMigrate: nil
)
]
}
}
Notice the type inside the fetch: WorkSchemaV2.WorkItem. Both values belong to that model, so this closure needs no cross-version model references or shared scratch array between callbacks. Apple’s MigrationStage.custom provides the before/after hooks; the intermediate schema supplies the overlap we need.
We calculate every converted value before assigning any of them. A negative duration or integer overflow therefore fails validation before this callback changes a row. Zero is a legitimate duration and converts to zero.
After validation, we update the existing rows and save. Errors propagate. A failed fetch must not look like an empty store, and a failed save must not look like a completed migration.
The retained minutes are authoritative throughout V2. Even if a V2 fixture contains partially prepared seconds, the callback recomputes them from minutes. Once V3 opens successfully, this stage is no longer needed, so reopening the app does not multiply the seconds again.
This implementation fetches the whole small store and keeps a second array of converted integers. That makes its validation rule easy to follow, but it is not a bounded-memory migration for millions of records. Profile migration time and memory with representative stores before adopting it for a large dataset.
Open the latest schema at the existing location
The fifth block creates the container:
nonisolated func openWorkStore(at url: URL) throws -> ModelContainer {
let schema = Schema(versionedSchema: WorkSchemaV3.self)
let configuration = ModelConfiguration(
"Work",
schema: schema,
url: url,
cloudKitDatabase: .none
)
return try ModelContainer(
for: schema,
migrationPlan: WorkMigrationPlan.self,
configurations: [configuration]
)
}
Call this once from the part of your app that owns the container, passing the existing store URL. Supply the resulting container to SwiftUI with .modelContainer(container). The factory throws so your startup flow can present a recovery screen if opening fails.
For an existing app, keep its actual store location and configuration name; "Work" is the example’s name, not a reason to rename yours. A newly created store at a different URL can make a broken migration look successful by quietly giving you an empty database.
The ordered SchemaMigrationPlan keeps all three schemas, allowing a V1 installation to reach V3 without installing an intermediate app. A fresh V3 store uses the current schema directly. Apple’s WWDC25 migration session revisits the same ordered-plan approach alongside newer SwiftData features.
Opening and migrating is synchronous work. Measure its startup cost; marking the factory nonisolated does not turn it into background work.
The example explicitly uses cloudKitDatabase: .none. It covers a local, single-owner store. CloudKit synchronization, app extensions sharing a store, and older clients still writing legacy values require additional coordination; don’t treat this local migration as a tested rollout plan for those systems.
A failed upgrade can leave an intermediate schema
This is the detail I would want to know before shipping.
In the disk-backed checks on macOS 27, a V1 record with an invalid negative duration reached V2, then failed conversion. Opening V3 threw. The fixture could still be opened as V2, and its original minutes, UUID, and title remained available.
The earlier lightweight stage had completed. The whole V1 → V3 path had not behaved like one all-or-nothing transaction.
That is an observed result on the tested runtime, not a promise about the exact file state after every possible failure. Design recovery to account for intermediate versions, and test the behavior on your supported OS versions. The full plan above includes V2 as a valid starting point.
Also, SwiftData surfaced a container-opening error rather than handing our caller the custom DurationMigrationError directly. Do not build recovery UI that depends on downcasting the thrown error to that enum. Retain useful diagnostics without logging users’ record contents.
On failure, keep the store and show an honest unavailable/recovery state. Automatically deleting it or silently switching to an in-memory container trades an opening error for missing data. A retry cannot make a negative duration valid; an explicit, tested repair or recovery path must resolve the underlying problem first.
Test the upgrade users actually run
The examples were compiled together, exactly as printed, for an iOS 17 simulator target and a macOS 14 target using Xcode 27 / Swift 6.4. Both ordinary isolation and MainActor default isolation were checked.
Compilation for those deployment targets is not a migration run on iOS or older macOS releases; those runtime paths still need testing.
The runtime checks use real, temporary SQLite stores on macOS 27. Each seed, upgrade, and reopen runs in a separate process, so an object retained by the test cannot stand in for persisted data. They cover:
- V1 → V3 with preserved UUIDs, Unicode titles, zero, and several nonzero durations.
- V2 → V3, including deliberately incorrect placeholder seconds.
- Reopening V3 and creating a new one-second record without converting it again.
- Negative and overflowing legacy values, a repeated failed open, and preservation of the retained V2 data.
- A fixture-only repair followed by a successful retry through the same plan.
- Fresh and empty stores, plus a larger set of distinct records to check for accidental loss or duplication.
For your app, keep store fixtures from released builds as well as synthetic edge cases. An in-memory container is useful for testing today’s models, but it cannot demonstrate that yesterday’s on-disk schema upgrades correctly. A store created by an unversioned release also needs its own fixture test; don’t assume reconstructing V1 from memory exactly matches what shipped.
The important handoff is small: keep the old value available until the new value has been computed and saved, then remove the old property. An intermediate schema gives that handoff somewhere durable to happen.