Search code examples
swiftenumsswiftdata

Non-class type 'MyEnum' cannot conform to class protocol 'PersistentModel'


How do i make the following enumType NotificationType to

conform to class protocol 'PersistentModel'

I'm using this for SwiftData schema. I can do a workaround and make var type: Int or some other type but it will make the code prone to errors and mistakes in long run.

enum NotificationType{
    case promotion, transaction
}

@available(iOS 17, *)
@Model
class NotificationObject {
    var id = UUID()
    ..
    var type: NotificationType
    ..    

    init(id: UUID = UUID(), type: NotificationType) {
        self.id = id
        self.type = type
    }
    
}

Any help is appericiated.


Solution

  • In SwiftData value types such as enum or struct need to conform to Codable to be correctly saved.

    enum NotificationType: Codable {
        case promotion, transaction
    }
    

    In SwiftData only classes can be used as model