I had a simple class called Entry with one field (timestamp: Date) and I tried to add a new field without having to uninstall the app , so I would not crash.
I tried implementing the MigrationPlan stuff but I do not know if I have to manually add a value to the new field or how exactly it works.
Here is my code. When I use the EntrySchemaV0 it works fine but if I try to use the V1 it crashes. (could not fetch ModelContainer) I also tried it with a custom migration stage. Crashes with error (SwiftData/BackingData.swift:432: Fatal error: Expected only Arrays for Relationships - String)
import Foundation
import SwiftData
enum EntrySchemaV0: VersionedSchema {
static var versionIdentifier = Schema.Version(0, 1, 0)
static var models: [any PersistentModel.Type] {
[Entry.self]
}
@Model
final class Entry {
var timestamp: Date
init(timestamp: Date) {
self.timestamp = timestamp
}
}
}
enum EntrySchemaV1: VersionedSchema {
static var versionIdentifier = Schema.Version(0, 2, 0)
static var models: [any PersistentModel.Type] {
[Entry.self]
}
@Model
final class Entry {
var name: String
var timestamp: Date
init(name: String = "", timestamp: Date = .now) {
self.name = name
self.timestamp = timestamp
}
}
}
enum EntryMigrationPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[EntrySchemaV0.self, EntrySchemaV1.self]
}
static var stages: [MigrationStage] {
[migrateV0toV1]
}
static let migrateV0toV1 = MigrationStage.lightweight(
fromVersion: EntrySchemaV0.self,
toVersion: EntrySchemaV1.self
)
}