I am currently in the middle of developing an iOS app which uses SwiftData. I want to future proof my data models by laying the ground work for data migrations down the line but I am pretty new to the whole thing and would appreciate some help.
My app currently has three SwiftData models and they are UserModelV1, EntryModelV1 and ImageModelV1.
import Foundation
import SwiftData
@Model
class UserModelV1 {
@Relationship var entries: [EntryModelV1] = []
var name: String
// Various Other Properties
}
import Foundation
import SwiftData
@Model
class EntryModelV1 {
@Relationship var images: [ImageModelV1]?
// Various Other Properties
}
import Foundation
import SwiftData
@Model
class ImageModelV1 {
// Various Properties
}
They all sit in a SchemaV1 folder alongside an AppSchemaV1 which has the following code:
import SwiftData
enum AppSchemaV1: VersionedSchema {
static var versionIdentifier = Schema.Version(1, 0, 0)
static var models: [any PersistentModel.Type] {
[
UserModelV1.self,
EntryModelV1.self,
ImageModelV1.self
]
}
}
I also created a mock up for UserModelV2 simulating some random changes to the model for testing purposes and placed it in a SchemaV2 folder with an AppSchemaV2 as such:
import Foundation
import SwiftData
@Model
class UserModelV2 {
@Relationship var entries: [EntryModelV1] = []
@Attribute(originalName: "name") var firstName: String
// Various Other Properties
}
import SwiftData
enum AppSchemaV2: VersionedSchema {
static var versionIdentifier = Schema.Version(2, 0, 0)
static var models: [any PersistentModel.Type] {
[
UserModelV2.self,
EntryModelV1.self,
ImageModelV1.self
]
}
}
I then created an AppMigration plan as such:
import SwiftData
enum AppMigrationPlan: SchemaMigrationPlan {
static var schemas: [any VersionedSchema.Type] {
[
AppSchemaV1.self,
AppSchemaV2.self
]
}
static var stages: [MigrationStage] {
[
.lightweight(
fromVersion: AppSchemaV1.self,
toVersion: AppSchemaV2.self
)
]
}
}
And finally a custom ModelContainerProvider as such:
import SwiftData
struct ModelContainerProvider {
static let shared: ModelContainer = {
do {
return try ModelContainer(
for: AppSchemaV1.self, // Error on this line
migrationPlan: AppMigrationPlan.self
)
} catch {
fatalError("Migration failed: \(error)")
}
}()
}
Finally I call the modelContainer in my app as such:
import SwiftData
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(ModelContainerProvider.shared)
}
}
The issue I'm getting is inside the ModelContainer Provider file above. I've highlighted the line that gives me the error and the exact error message is below:
Cannot convert value of type 'AppSchemaV1.Type' to expected argument type 'Schema'
I'm not entirely sure how to fix this issue and am also wondering if I am going along the right lines in regards to setting up my data migrations or if I'm way off.
I'd appreciate any help. Thanks in advance.