skip to content

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%

answer

  1. two closures, two shapes
  2. before: new fields missing
  3. after: old field gone
  4. a bridge version holding both

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.

solid answer

~40 s

A `.custom` stage straddles one schema change. `willMigrate` sees the store in the source shape, where `travelerName` exists but `firstName` and `lastName` do not; `didMigrate` sees the destination shape, where the new fields exist and `travelerName` has already been removed with its values. So a V2-to-V4 stage that copies in `didMigrate` reads nothing and writes empty strings. The fix is a **bridge version**: V3 keeps `travelerName` and adds `firstName` and `lastName`, a custom V2-to-V3 stage fills them in `didMigrate`, and a `.lightweight` V3-to-V4 stage drops `travelerName`. Schema versions are steps, not releases, so V3 and V4 can ship together and the container runs both stages in one open.

code

swift · 46 lines
swift
import Foundation
import SwiftData

enum TripSchemaV2: VersionedSchema {
    static let versionIdentifier = Schema.Version(2, 0, 0)
    static var models: [any PersistentModel.Type] { [Trip.self] }
    @Model final class Trip { var travelerName = ""; init() {} }
}

enum TripSchemaV3: VersionedSchema {   // bridge: old and new fields side by side
    static let versionIdentifier = Schema.Version(3, 0, 0)
    static var models: [any PersistentModel.Type] { [Trip.self] }
    @Model final class Trip {
        var travelerName = ""
        var firstName = ""
        var lastName = ""
        init() {}
    }
}

enum TripSchemaV4: VersionedSchema {
    static let versionIdentifier = Schema.Version(4, 0, 0)
    static var models: [any PersistentModel.Type] { [Trip.self] }
    @Model final class Trip { var firstName = ""; var lastName = ""; init() {} }
}

enum TripMigrationPlan: SchemaMigrationPlan {
    static var schemas: [any VersionedSchema.Type] {
        [TripSchemaV2.self, TripSchemaV3.self, TripSchemaV4.self]
    }
    static var stages: [MigrationStage] {
        [
            .custom(fromVersion: TripSchemaV2.self, toVersion: TripSchemaV3.self,
                    willMigrate: nil,
                    didMigrate: { context in
                        for trip in try context.fetch(FetchDescriptor<TripSchemaV3.Trip>()) {
                            let parts = trip.travelerName.split(separator: " ", maxSplits: 1)
                            trip.firstName = parts.first.map(String.init) ?? ""
                            trip.lastName = parts.count > 1 ? String(parts[1]) : ""
                        }
                        try context.save()
                    }),
            .lightweight(fromVersion: TripSchemaV3.self, toVersion: TripSchemaV4.self),
        ]
    }
}

go deeper

for a junior

Recall that a custom stage has two closures: willMigrate before the schema change and didMigrate after it.

for a middle

Explain what each closure can see: the old attributes before the move, the new ones after it, never both in one stage.

for a senior

Diagnose silent data loss in a split or merge and fix it with a bridge version holding both shapes, followed by a lightweight stage that drops the old field.

for a principal

Weigh dropping the old field now against keeping it a while, and how many extra versions the plan should carry for the sake of simple stages.

## Two closures, two shapes `MigrationStage.custom(fromVersion:toVersion:willMigrate:didMigrate:)` wraps one schema change with two optional closures, each handed a `ModelContext`: - **`willMigrate`** runs first, while the store still has the **source** version's attributes. - **`didMigrate`** runs after the store has been moved to the **destination** version's attributes. No moment inside a single stage has both the old attribute and the new ones in the store. That is fine for most fixes, because they need only one side: de-duplicating needs the old shape, filling a default from other new fields needs the new one. A **split** needs both: read `travelerName`, write `firstName` and `lastName`. ## Why the names come out empty | Closure | Store shape | `travelerName` | `firstName` / `lastName` | |---|---|---|---| | `willMigrate` (V2 to V4) | V2 | Readable | Not in the store yet | | `didMigrate` (V2 to V4) | V4 | Already removed | Present, holding defaults | A single V2-to-V4 stage that copies in `didMigrate` therefore loops over trips whose old names are gone, and the new fields keep their empty defaults. Nothing throws: the migration succeeds and the data is lost, a particularly dangerous kind of migration bug because it ships quietly. ## The bridge-version plan A reliable fix adds a version that exists only to hold both shapes at once: 1. **V3, the bridge:** keeps `travelerName` and adds `firstName` and `lastName` with defaults. 2. **Stage V2 to V3, custom:** adding the fields needs no help, so `willMigrate` is `nil`; `didMigrate` runs on the V3 shape, where both sides exist, splits each name, writes the parts and saves. 3. **V4, the target:** only `firstName` and `lastName`. 4. **Stage V3 to V4, lightweight:** dropping `travelerName` is a removal SwiftData infers. 5. **The plan** lists `[TripSchemaV2.self, TripSchemaV3.self, TripSchemaV4.self]` and both stages, and the app's typealias points at V4. When a user with a V2 store installs the release, the container runs the V2-to-V3 stage and then the V3-to-V4 stage in the same open. ## Writing the didMigrate step The copy itself is ordinary model code, run against the bridge version's types: - Fetch `TripSchemaV3.Trip`, the frozen bridge type, not the app's typealias, which points at V4 and has no `travelerName`. - Decide the splitting rule for awkward data: a single word, extra spaces, an empty string, a family name with several words. The example keeps everything after the first space as the last name. - Call `try context.save()` at the end; the stage does not save for you. - Keep the step deterministic: it reads only `travelerName`, so running it on any V2 store gives the same result. The rule you pick here is a product decision about user data, so write it down next to the code and test it with real names, not only "Ada Lovelace". ## Versions are not releases It helps to separate two numbering schemes: - **App releases** are what users install. - **Schema versions** are steps in the plan. One release can add several, as V3 and V4 do here. - No build of the app uses the bridge as its current model; it exists only so a stage has both shapes available. - Once shipped, V3 is frozen like any other version, because some future store could still need to pass through it. - New installs never touch the bridge: with no store on disk, the container creates one directly in the V4 shape and no stage runs. ## Alternatives and their costs - **Stop at V3.** Keep `travelerName` and never drop it. Simpler, but the stale field lingers and someone eventually writes to the wrong one. - **Stash values between the closures.** `willMigrate` reads names into a store that `didMigrate` writes from. Both closures are `@Sendable`, so the stash must be thread-safe and keyed by a value that survives the move, such as the booking reference. It works, with more code to get right than a bridge version. - **Split at read time.** Leave the data alone and compute first and last names in code. It avoids a migration, but the names cannot be queried or sorted as stored attributes. The same reasoning covers **merging** two fields into one, or **converting a type**: whenever a stage must read an attribute that the destination removes and write one that the source lacks, put a version in between that holds both.

  • Do the SwiftData bridge version and the final version have to ship in separate app releases?
    No. Schema versions are steps in the plan, not releases. Both can ship in the same update: when the container opens a V2 store, it runs the V2-to-V3 custom stage and then the V3-to-V4 lightweight stage in the same open, and the app only ever works with the V4 types.
  • Could willMigrate stash the old names for didMigrate to write instead?
    It can, but both closures are `@Sendable`, so the stash needs a thread-safe store, and it must be keyed by a stored value that survives the move, such as the booking reference. It is more code to get right than a bridge version, and the bridge keeps each closure working against one clear shape.

Moving house with no overlap: before the handover you can only pack in the old house, and after it you can only unpack in the new one, so anything left unpacked is lost. A few days holding both sets of keys, the bridge version, lets you carry everything across before the old house goes.

  • didMigrate can still read travelerName because the stage has not finished yet.
  • willMigrate can write firstName because the destination fields already exist.
  • Each schema version has to correspond to exactly one App Store release.
  • A lightweight stage can split a string if originalName points at it.