# Test SwiftData Schema Migrations on a Remote Mac

Canonical: https://figment.so/blog/mac-swiftdata-migration-remote

Seed a v1 store in XCTest setup, open it with the migration plan, and assert counts, attributes and relationships on v2. Run it with xcodebuild test; the Intel Mac VM ($25 a month) fits Xcode 26.3 or earlier, Apple silicon plans fit newer Xcode.

**Seed a v1 SwiftData store in XCTest setup, open it with your `SchemaMigrationPlan`, and assert that entity counts, attributes and relationships survive on v2, then run the suite with `xcodebuild test` on a remote Mac before you submit to App Store Connect.** A shipped SwiftData app has one chance to migrate each user's store correctly, and this catches entity-count drops, missing relationships and silent type coercions in CI instead of in a review. SwiftData is available on macOS 14+ and iOS 17+.

## How do SwiftData versioned schemas work?

SwiftData uses `VersionedSchema` conformances to pin your model at a point in time. Each released version becomes a named enum that lists the `@Model` classes active in that release and declares a `static var versionIdentifier: Schema.Version`.

A [`SchemaMigrationPlan`](https://developer.apple.com/documentation/swiftdata/schemamigrationplan) orders those versions into a sequence of `MigrationStage` values via `static var schemas` and `static var stages`. SwiftData reads the existing store's version, finds the gap to the current schema, and walks each stage in order. When you initialize `ModelContainer` with that `migrationPlan`, the walk runs automatically before your app or your test performs any fetch.

The [`MigrationStage`](https://developer.apple.com/documentation/swiftdata/migrationstage) enum defines two cases:

| Stage | Use when |
|---|---|
| `lightweight(fromVersion:toVersion:)` | Adding optional attributes, renaming with `@Attribute(.originalName)`, changing a delete rule |
| `custom(fromVersion:toVersion:willMigrate:didMigrate:)` | Making a property unique, transforming values, splitting or merging entities |

A lightweight stage requires no code, because SwiftData infers the mapping. A custom stage gives you two optional `(ModelContext) throws -> Void` closures: `willMigrate` runs before the new schema is applied (old models are reachable), and `didMigrate` runs after (only new models are reachable).

## How do I define two schema versions?

Put both versions in one file so the migration plan can reference them side by side. Note that `AppSchemaV1.Item` and `AppSchemaV2.Item` are distinct namespaced types, which is SwiftData's recommended pattern for coexisting schema versions.

```swift
import SwiftData

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

    @Model final class Item {
        var title: String
        var createdAt: Date
        init(title: String, createdAt: Date = .now) {
            self.title = title
            self.createdAt = createdAt
        }
    }
}

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

    @Model final class Item {
        var title: String
        var createdAt: Date
        var priority: Int          // new required attribute
        var tags: [String]         // new attribute
        init(title: String, createdAt: Date = .now, priority: Int = 0, tags: [String] = []) {
            self.title = title
            self.createdAt = createdAt
            self.priority = priority
            self.tags = tags
        }
    }
}

enum AppMigrationPlan: SchemaMigrationPlan {
    static var schemas: [any VersionedSchema.Type] { [AppSchemaV1.self, AppSchemaV2.self] }
    static var stages: [MigrationStage] { [v1ToV2] }

    static let v1ToV2 = MigrationStage.custom(
        fromVersion: AppSchemaV1.self,
        toVersion: AppSchemaV2.self,
        willMigrate: { context in
            let oldItems = try context.fetch(FetchDescriptor<AppSchemaV1.Item>())
            _ = oldItems // inspect or transform here
            try context.save()
        },
        didMigrate: { context in
            let items = try context.fetch(FetchDescriptor<AppSchemaV2.Item>())
            for item in items {
                item.priority = 0
                item.tags = []
            }
            try context.save()
        }
    )
}
```

## What does the XCTest migration test look like?

This is a reviewed template, not output from a measured run. Adapt the `@Model` types, module name, and scheme to your own project, verify initializer labels against the SwiftData reference for your Xcode version, and compile it locally before wiring it into CI.

```swift
import XCTest
import SwiftData
@testable import MyApp

final class SwiftDataMigrationTests: XCTestCase {

    private var storeURL: URL!

    override func setUpWithError() throws {
        let dir = FileManager.default.temporaryDirectory
        storeURL = dir.appendingPathComponent("migration_test_\(UUID().uuidString).store")

        let v1Schema = Schema([AppSchemaV1.Item.self])
        let v1Config = ModelConfiguration(schema: v1Schema, url: storeURL)
        let v1Container = try ModelContainer(for: v1Schema, configurations: [v1Config])
        let ctx = ModelContext(v1Container)

        for i in 1...10 {
            ctx.insert(AppSchemaV1.Item(title: "Item \(i)", createdAt: .now))
        }
        try ctx.save()
    }

    override func tearDownWithError() throws {
        guard let url = storeURL else { return }
        try? FileManager.default.removeItem(at: url)
        storeURL = nil
    }

    private func openV2() throws -> ModelContext {
        let container = try ModelContainer(
            for: AppSchemaV2.Item.self,
            migrationPlan: AppMigrationPlan.self,
            configurations: ModelConfiguration(url: storeURL)
        )
        return ModelContext(container)
    }

    func testMigrationPreservesItemCount() throws {
        let ctx = try openV2()
        let items = try ctx.fetch(FetchDescriptor<AppSchemaV2.Item>())
        XCTAssertEqual(items.count, 10, "Migration must preserve all 10 items")
    }

    func testMigrationSetsPriorityDefault() throws {
        let ctx = try openV2()
        let items = try ctx.fetch(FetchDescriptor<AppSchemaV2.Item>())
        XCTAssertTrue(
            items.allSatisfy { $0.priority == 0 },
            "Migrated items should have priority 0 until the user updates them"
        )
    }

    func testMigrationPreservesTitlesAndDates() throws {
        let ctx = try openV2()
        var descriptor = FetchDescriptor<AppSchemaV2.Item>(
            sortBy: [SortDescriptor(\AppSchemaV2.Item.createdAt)]
        )
        descriptor.fetchLimit = 10
        let items = try ctx.fetch(descriptor)
        XCTAssertEqual(items.count, 10)
        XCTAssertNotNil(items.first?.createdAt)
        XCTAssertTrue(items.allSatisfy { $0.title.hasPrefix("Item ") })
    }
}
```

Run the suite over SSH against a simulator that matches the Xcode installed on the Mac. Replace `MyApp.xcodeproj`, `MyApp`, and the test target name with your own project's values, and pick a simulator name that `xcrun simctl list devices` actually returns:

```bash
xcodebuild test \
  -project MyApp.xcodeproj \
  -scheme MyApp \
  -destination 'platform=iOS Simulator,name=iPhone 16' \
  -only-testing:MyAppTests/SwiftDataMigrationTests \
  -resultBundlePath ./MigrationTestResults.xcresult
```

`xcodebuild test` returns non-zero on any test failure, so your CI job fails the pipeline since a failed build is never a passing migration result.

## Should I use a lightweight or a custom stage?

Before writing any `willMigrate` code, check whether the change qualifies for a lightweight stage.

**Lightweight fits** adding a new optional attribute (SwiftData sets it to `nil`), renaming a property with `@Attribute(.originalName("oldName"))`, or changing a relationship's delete rule.

**Custom is required** for making an attribute unique, splitting one attribute into two (`fullName` → `firstName` + `lastName`), changing a property's type (e.g., `String` to `Date`), or populating a new required attribute from a computed value.

The order of stages in `SchemaMigrationPlan.stages` matters: SwiftData walks them sequentially. If you release v1 → v2 as lightweight and v2 → v3 as custom, both must appear in `stages` in that order.

## Which migration failures should CI catch?

**Renamed attribute drops data.** Renaming without `@Attribute(.originalName(...))` is treated as delete-plus-add, dropping the original values. Add `originalName` before shipping or write a custom stage that copies the data.

**Dropped relationship leaves orphans.** Removing a relationship without a delete rule can leave related records behind. Set `.cascade` or `.nullify` on the parent side in the schema version *before* the one that removes the relationship.

**Type change without a transform throws.** Changing `var score: String` to `var score: Double` without a custom `willMigrate` closure produces a runtime migration error. Transform the string values to doubles inside `willMigrate` before the new schema applies.

**Missing save in `willMigrate`.** The closure receives a `ModelContext`; call `try context.save()` before it returns or SwiftData discards your changes.

Write one XCTest for each failure mode above against a realistic seeded store. Those four tests pay for themselves the first time a reviewer renames a field in a hotfix branch.

## Does the Xcode version set the plan for SwiftData migration tests?

The migration suite needs only `xcodebuild test` and a simulator, so the Xcode version decides the plan. The [Intel Mac VM](/mac-hosting#intel-vm) ($25 a month, $2 a day) runs macOS Sequoia with Xcode 26.3 or earlier. Choose the [Apple Silicon Mac VM](/mac-hosting#apple-silicon-vm) ($39 a month, $6 a day) for Xcode 26.4 or later, Xcode 27, arm64-only simulator runtimes or visionOS, and check the macOS version shown before purchase against Apple's Xcode table.

**Related reading:**
- [Automate Xcode UI Tests on a Remote Mac](/blog/mac-ui-testing-xcode-remote-mac)
- [Test App Clip Experiences on a Remote Mac](/blog/mac-app-clip-testing-remote-mac)
- [Run GitHub Actions on a Self-Hosted Mac Runner](/blog/mac-github-actions-self-hosted-runner)
