This post presents an implementation of a Swift enum property on a Core Data Model. Following the method in this post will allow you to get and set a model property using an enum type.

Create Enum

The first step is to create a representative enum for a model property. For this example, a State enum will be created with the cases on, off, and unknown.

enum State: Int32 {
    case off = 0
    case on = 1
    case unknown = 2
}

Create A Core Data Model

The next step is to create a Core Data Model called StatefulModel. One solution to save Swift enums in Core Data is to create a corresponding Int32 property and implement a custom getter and setter. First, create a stateValue property with the type Int32 on a new Core Data Model.

Next, implement the following extension for StatefulModel:

extension StatefulModel {
    var state: State {
        // To get a State enum from stateValue, initialize the
        // State type from the Int32 value stateValue
        get {
            return State(rawValue: self.stateValue)!
        }

        // newValue will be of type State, thus rawValue will
        // be an Int32 value that can be saved in Core Data
        set {
            self.stateValue = newValue.rawValue
        }
    }
}

Saving a Swift Enum To Core Data

That’s it! The StatefulModel now has an enum property that supports both get and set.

let context = // your Core Data Managed Object Context

// Create a new Stateful Model
let entityDescription = NSEntityDescription.entity(
    forEntityName: “StatefulModel”,
    in: context
)!
        
let model = StatefulModel(
    entity: entityDescription, 
    insertInto: context
)

// Set a new state
model.state = .on

// Get and print the State enum value
print(model.state)

// Save the Stateful Model
try! context.save()