Yimin Pang Yimin Pang - 5 months ago 56
Swift Question

Using enumeration type value in Core Data Entity

How to use enumeration type value in Core Data Entity attribute? except choosing transformable.


You can't store the enumeration type directly, because Core Data doesn't understand Swift enums. You'll need to declare the enumeration to have a raw value of some kind, and save the raw value in Core Data. Something like

enum Bar : Int {
    case bar1;
    case bar2;

let myBar = Bar.bar1

// Then save myBar.rawValue in Core Data as an integer type

When reading, get the integer value from Core Data and convert it to the enumeration as

let rawValue = managedObject.bar
let value = Bar(rawValue: rawValue)