I have an app with some SwiftData Models. One is called Tapas and it has a relationship with TapasAsana. One Tapas has many Asanas, so I connected them with a relationship. This all works wonderful so far.
Now I just forgot one property in TapasAsana. I read about light migration and it should be easy to just add that property. But no matter if I add it at the end or in the middle of the properties it breaks my app. The app compiles and runs, but the old Data doesn't get shown anymore. And cretaing new ones in the app also won't work, trying to directly create a TapasAsana crashes the App.
This is the code for the TapasAsana Model, the one where I am adding a property. The new property is called recoupCount.
import Foundation
import SwiftData
@Model
class TapasAsana {
var name: String
var duration: Int /// How long to execute daily
var timeToday: Int /// Time done already today
var recoupCount: Int /// How many recoups this Asana has.
var polar: Bool /// If it is a polar Asana
var doneToday: Bool /// If it is completed today
init(name: String = "Padahastasana", duration: Int = 5 * 60, timeToday: Int = 0, recoupCount: Int = 0, polar: Bool = false, doneToday: Bool = false) {
self.name = name
self.duration = duration
self.timeToday = timeToday
self.recoupCount = recoupCount
self.polar = polar
self.doneToday = doneToday
}
}
I tried to just add the new Property, to add it at the last position to not confuse SwiftData with the order. But none of that works. I didn't try more because reading about migration said the simple add of a property should work fine.
You need to give your new property a default value for a lightweight migration to work and it must be where it's declared, doing so in the init parameter list isn't enough.
@Model
class TapasAsana {
//...
var recoupCount: Int = 0
//...
}