Regarding the Preview issue with SwiftData

I referred to the code provided in the article Adding and Editing Persistent Data in Your App in the SwiftData documentation and tested the "/PreviewHelper" approach. I found that if a model class contains a property of a struct, and that struct includes a Set property or an Array property, the Preview would throw an error. Here is an example of the model:

@Model
class Book {
    // ...
    var someStruct: SomeStruct
    // ...
}

struct SomeStruct: Codable {
    // ...
    var someCollection: Set<Int>
    // ...
}

In actuality, this model can run and store data without any issues, but it fails to run in the Preview. Is there a problem with the implementation of this Preview or is there any other reason? Are there better ways to perform Preview in SwiftData?

Replies

Hi,

Sorry to hear you are having problems getting previews and SwiftData working. Could you provide an example of what your Preview definition looks like, and what the error you see when using it?

  • After retesting multiple times, I found that the problem arises when defining an enumeration within a structure. The issue is that the raw value type must be specified; otherwise, the preview crashes with the message "Preview Crashed." The preview definition matches the code provided in the official documentation. I have attached a sample code snippet of the model for reference.

Add a Comment