0

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!

10
  • 3
    You didn't initialise items. Commented Nov 7, 2023 at 3:34
  • 2
    It's a fundamental requirement of a Swift initialiser. Nothing to do with SwiftData or relationships. Commented Nov 7, 2023 at 3:56
  • 3
    That video was created with an Xcode beta, so it probably had some bugs Commented Nov 7, 2023 at 4:03
  • 1
    This question is not a duplicate of the one linked. That one is about failure to initialise an optional let. This is about failure to initialise a non optional var. The rules are different. Commented Nov 7, 2023 at 10:47
  • 1
    @MichaelMay you could make it optional, but why not just initialise it to an empty array? Commented Nov 7, 2023 at 10:48

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Thanks for your participation, everyone. I agree with the solution by some of you that a default value can be provided to the items var or items can be declared as an Optional.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.