Skip to main content

Lightweight vs complex migrations

About 1 minSwiftArticle(s)bloghackingwithswift.comcrashcourseswiftswiftdataxcodeappstore

Lightweight vs complex migrations 관련

SwiftData by Example

Back to Home

Lightweight vs complex migrations | SwiftData by Example

Lightweight vs complex migrations

Updated for Xcode 15

SwiftData is able to handle us renaming model properties through an automatic lightweight migration, however you do need to use the @Attribute macro to tell it the original name of the property.

For example, you might start off with a User model such as this one:

@Model
class User {
    var name: String

    init(name: String) {
        self.name = name
    }
}

However, you might later decide that fullName would have been a better name for the property. That's where the @Attribute macro comes in, because it lets you specify the original name used for the property so that SwiftData can move from old to new on your behalf. Here's how that looks:

@Model
class User {
    @Attribute(originalName: "name") var fullName: String

    init(name: String) {
        self.fullName = name
    }
}

That tells SwiftData to use the fullName property going forward, but if it finds an older model version using name it will be upgraded automatically – it will be renamed for us to the new name without any further intervention from us.

Tips

If you change the property name without using Attribute(originalName:), SwiftData will consider the old and new properties to be different things in your schema, and so it won't migrate between the two. If you want to discard the old data and create a new property then go for it, but if you want to avoid data loss make sure to use @Attribute.


이찬희 (MarkiiimarK)
Never Stop Learning.