Modeling complex value type in SwiftData

I just saw the available video according SwiftData and wanted to convert a project of mine.

Both documentation and video mention this:

By default, SwiftData includes all noncomputed properties of a class as long as they use compatible types. The framework supports primitive types such as Bool, Int, and String, as well as complex value types such as structures, enumerations, and other value types that conform to the Codable protocol.

I tried to model an enum but I always get an error regarding the conformance to PersistentModel

I made different type of enum all implementing RawRepresentable but I always get an error

For example:

enum Simple: Int16 {
    case one, two
}
 @Model
class Item {
    var simple: Simple = .one
}

I got those errors:

No exact matches in call to instance method 'getValue' Candidate requires that 'Simple' conform to 'PersistentModel' (requirement specified as 'Value' : 'PersistentModel') Candidate requires that 'Simple' conform to 'Sequence' (requirement specified as 'Value' : 'Sequence')

Did I miss something here?

Accepted Reply

Hello,

  1. Conform Enum to Codable
  2. Remove default value

Boom 🤷🏻

  • Seems to work 🤯 I hope that some more information will be added to the documentation

  • Good to know the enum has to conform to Codable! Nevertheless this isn’t working for me – the enum won’t be persisted when changing in the app.

  • But sadly, CloudKit integration is requiring default value for every property 🥲

Add a Comment

Replies

Hello,

  1. Conform Enum to Codable
  2. Remove default value

Boom 🤷🏻

  • Seems to work 🤯 I hope that some more information will be added to the documentation

  • Good to know the enum has to conform to Codable! Nevertheless this isn’t working for me – the enum won’t be persisted when changing in the app.

  • But sadly, CloudKit integration is requiring default value for every property 🥲

Add a Comment