Search code examples
swiftswiftdata

SwiftData: Return from initializer without initializing all stored properties


everyone. I encountered the error message in the title of this post thrown by Xcode 15.0.1 for the following code which uses SwiftData with SwiftUI:

import SwiftUI
import SwiftData

@Model
final class PorcelineTile {
    @Attribute (.unique) var name: String
    var additionalInfo: String
    var pattern: [String: Double]

    init(name: String, pattern: [String: Double] = ["":0.0], additionalInfo: String = "") {
        self.name = name
        self.additionalInfo = additionalInfo
        self.pattern = pattern
    }

    @Relationship(deleteRule: .cascade) var items: [Item]
}

I have tried commenting out any one or two of the three properties and their corresponding mappings in the initialiser but the error message just wouldn't go away. I'm really puzzled what could've gone wrong. Thanks a lot for your help!


Solution

  • Initialize items property as an empty array of Item like this:

    @Relationship(deleteRule: .cascade) var items: [Item]()
    

    Now you shouldn't have to make it optional or provide a default value.