// // Models.swift // SwiftDataDemo // // Created by Vencent on 2023/6/12. // import Foundation import SwiftData @Model class Person { // 身份证号 @Attribute(.unique) let id: UUID // 姓名 @Attribute(.unique) var name: String // 生日 var birthday: Date // 朋友 var friends: [Person] = [] // 愿望 @Relationship(.cascade) var wishList: [Wish] = [] init(name: String, friends: [Person], wishList: [Wish]) { self.id = UUID() self.name = name self.birthday = Date() self.friends = friends self.wishList = wishList } } @Model class Wish { /// 内容 var content: String /// 拥有者姓名 var owner: String init(content: String, owner: String) { self.content = content self.owner = owner } } enum SchemaV1: VersionedSchema { static var versionIdentifier: String? = "SchemaV1" static var models: [any PersistentModel.Type] { [Person.self, Wish.self] } @Model class Person { // 身份证号 @Attribute(.unique) let id: UUID // 姓名 var name: String // 生日 var birthday: Date // 朋友 var friends: [Person] = [] // 愿望 @Relationship(.cascade) var wishList: [Wish] = [] init(name: String, friends: [Person], wishList: [Wish]) { self.id = UUID() self.name = name self.birthday = Date() self.friends = friends self.wishList = wishList } } @Model class Wish { /// 内容 var content: String /// 拥有者姓名 var owner: String init(content: String, owner: String) { self.content = content self.owner = owner } } } enum SchemaV2: VersionedSchema { static var versionIdentifier: String? = "SchemaV2" static var models: [any PersistentModel.Type] { [Person.self, Wish.self] } } enum MigrationPlan: SchemaMigrationPlan { static var schemas: [VersionedSchema.Type] { [SchemaV1.self, SchemaV2.self] } static var stages: [MigrationStage] { [migrateV1toV2] } static var migrateV1toV2 = MigrationStage.custom( fromVersion: SchemaV1.self, toVersion: SchemaV2.self, willMigrate: { context in print("willMigrate") }, didMigrate: { context in print("didMigrate") } ) }