Modify exsiting data model in SwiftData

I need to add a new property to a class modeled in SwiftData after the project has been compiled and some data already been saved to the underlying container. But the app crashed when I tried to build and run the project with the modified data model. For example, the data model is as follows:

import Foundation
import SwiftData

final class TileView {
    @Attribute (.unique) var tileName
    var tileLegth: Double
    var tileWidth: Double
    var tilePatternName: String
    // var tileType: String // This is later added

   init(tileName: String, tileLength: Double, tileWidth: Double, tilePatternName: Double/*, tileType: String*/) {
       self.tileName = tileName
       self.tileLength = tileLength
       self.tilePatternName = tilePatternName
       // self.tileType = tileType

When the commented code in the above code snippet is uncommented after the app has been built and run initially, the app crashes if it is built and run subsequently. Is there a safe way to modify (e.g. add to or remove properties) existing models like the above? Thank you so much.


  • Problem solved. It's because I didn't migrate the @Relationship var, so the runtime couldn't find it in the new version of the model. Sorry, I didn't put the @Relationship var in the code snippet I provided in my post because I didn't know it was the missing of the @Relationship var in the initialiser of the new version that had caused the problem.

    Thank you for your participation and suggestions.