Storing a Swift Enum in Core Data

You must do the following to store a Swift enum in Core Data:

  • Create an enum with a raw value with a type Core Data can store, such as an integer or a string.
  • Add an attribute for the enum to the Core Data entity. Set the attribute’s type to the raw value type.
  • Add a computed property to the entity to convert the enum to and from the attribute’s raw value.

Creating the Enum

Core Data has no way of knowing your enum. That’s why you must give your enum a raw value type. Supplying a raw value type lets Core Data store the enum value.

The following code shows an enum for issue priorities whose raw value type is an integer:

Core Data will save the integer values of the issue priorities.

Adding the Computed Property

Adding a computed property to the Core Data entity allows you to use the Swift enum in your code. The usual way to add a computed property is to create an extension for the Core Data entity type.

The computed property requires a getter and a setter. The getter creates an enum value from its raw value. The setter sets the raw value for the enum value.

The next example shows an Issue entity with a priorityLevel attribute of type Int64. The following code creates a computed property for the issue priority:

Now you can use the priority property to set issue priorities using the enum values.

When writing the setter make sure to use the same data type as the attribute in the Core Data model, Int64 in the example.