Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Storing states in CoreData with enums

I want to store an enum state for a managed object within CoreData

enum ObjStatus: Int16 {
    case State1 = 0
    case State2 = 1
    case State3 = 3
}

class StateFullManagedObject: NSManagedObject {
    @NSManaged var state: Int16
}

The last step would be converting the state var of StateFullManagedObject to ObjStatus for direct comparison, which isn't working for me. For example, I can't use the == operator between and Int16 and the Int16 enum. The compile time error I get is

Int16 is not convertible to 'MirrorDisposition'

. See the conditional below:

var obj: StateFullManagedObject = // get the object

if (obj.state == ObjStatus.State1) { // Int16 is not convertible to 'MirrorDisposition'

}

How can I compare/assign between an Int16 and an enum?

like image 552
kev Avatar asked Oct 15 '22 23:10

kev


People also ask

Should enums be capitalized Swift?

The name of an enum in Swift should follow the PascalCase naming convention in which the first letter of each word in a compound word is capitalized.

Can enums inherit Swift?

In Swift language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.

Can Swift enums have methods?

Swift's Enum can have methods. It can have instance methods and you can use it to return expression value for the UI. Let's look at the code above. I defined a string array named marriedStrings using the fireprivate access limiter.


2 Answers

You can declare your enum as @objc. Then it all automagically works. Here's a snippet from a 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 to type Integer 32.

like image 105
Mark Krenek Avatar answered Oct 17 '22 12:10

Mark Krenek


You can extract raw Int16 value with .rawValue property of ObjStatus.

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

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

But you might want 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:
    //...
}
like image 62
rintaro Avatar answered Oct 17 '22 11:10

rintaro