Swift: saving states in CoreData with enumerations

I want to save the enumeration state for a managed object in CoreData

enum ObjStatus: Int16 { case State1 = 0 case State2 = 1 case State3 = 3 } class StateFullManagedObject: NSManagedObject { @NSManaged var state: Int16 } 

The final step is to convert the var StateFullManagedObject state to ObjStatus for direct comparison, which does not work for me. For example, I cannot use the == operator between an Int16 and an Int16 enumeration. The compile time error that I get is

Int16 does not convert to 'MirrorDisposition'

. See legend below:

 var obj: StateFullManagedObject = // get the object if (obj.state == ObjStatus.State1) { // Int16 is not convertible to 'MirrorDisposition' } 

How can I compare / assign between Int16 and enumeration?

+31
swift core-data
Nov 13 '14 at 2:24
source share
2 answers

You can extract the raw Int16 value using the .rawValue ObjStatus .

 // compare obj.state == ObjStatus.State1.rawValue // store obj.state = ObjStatus.State1.rawValue 

But you may need to implement stateEnum accessor for it:

 class StateFullManagedObject: NSManagedObject { @NSManaged var state: Int16 var stateEnum:ObjStatus { // ↓ If self.state is invalid. get { return ObjStatus(rawValue: self.state) ?? .State1 } set { self.state = newValue.rawValue } } } // compare obj.stateEnum == .State1 // store obj.stateEnum = .State1 // switch switch obj.stateEnum { case .State1: //... case .State2: //... case .State3: //... } 
+34
Nov 13 '14 at 2:49
source share

You can declare your listing as @objc. Then it all works automatically. Here is a snippet of the project I'm working on.

 // Defined with @objc to allow it to be used with @NSManaged. @objc enum AgeType: Int32 { case Age = 0 case LifeExpectancy = 1 } /// The age type, either Age or LifeExpectancy. @NSManaged var ageType: AgeType 

In the Core Data model, ageType is set for Integer 32 input.

+44
Jul 28 '15 at 16:16
source share



All Articles