Core Data Enums

One way to store an enum in core data is to actually store an Int value and then translate the integer into the enum when used.

Create a new Integer 16 attribute

Define your enum. If you make the enum Equatable and CaseIterable you can use a Picker to change its values.

public enum MyEnum: Int16, Equatable, CaseIterable {
    case zero = 0
    case one = 1
    case two = 2
    
    var stringValue: String {
        switch self {
        case .zero:
            return "Zero"
        case .one:
            return "First"
        case .two:
            return "Second"
    }
}

Create a getter and setter, in the class or extension for your model, that converts the value stored in core data to an instance of MyEnum. Optionally provide a default value if the conversion fails.

public var myEnum: MyEnum {
    get {
        return MyEnum(rawValue: myEnumValue) ?? .zero
    }
    set {
        self.myEnumValue = newValue.rawValue
    }
}

You can then write to and read from the enum like a normal swift value.

SwiftUI Picker

If you want the user to be able to modify the value themselves, you can use a Picker in swiftui.

Picker (
    selection : Binding (
        get : { myModel.myEnum },
        set : { value in
            self.myModel.myEnum = value
        }
    ),
    label : Text ("Select value")
) {
    ForEach (MyEnum.allCases, id: \.self.rawValue) {
        value in Text (value.stringValue).tag (value.rawValue)
    }
}
Last Updated February 16, 2021