Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist custom enum with SwiftData?

I want to save a custom enum to my SwiftData model. I can get it to work that it shows and even updates the value in the UI. Though, the change of the enum var/entity isn’t persisted when relaunching the app!

Any advice what to watch out for when using custom enums?

My Model

enum Type: Int, Codable {
    case foo = 0
    case bar = 1
}

@Model
final public class Item {
    var type: Type
}

UI Code

struct DetailView: View {
    @Bindable var item: Item
    
    // MARK: -
    var body: some View {
        Picker("Type", selection: $item.type) {
            Text("Foo").tag(Type.foo)
            Text("Bar").tag(Type.bar)
        }
        .pickerStyle(.segmented)
    }
}
like image 254
alexkaessner Avatar asked Sep 11 '25 08:09

alexkaessner


1 Answers

This solution work for me. Hopefully enums will be fixed in future versions of SwiftData.

enum SomeType: Int, Codable {
    case foo = 0
    case bar = 1
}

@Model
final public class Item {
    
    @Transient var type: SomeType {
        get { SomeType(rawValue: _type)! }
        set { _type = newValue.rawValue }
    }
    
    @Attribute var _type: SomeType.RawValue
    
} 
like image 85
Andrei Durymanov Avatar answered Sep 13 '25 22:09

Andrei Durymanov