本文介绍了Swift:使用枚举在 CoreData 中存储状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 CoreData 中存储托管对象的枚举状态

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
}

最后一步是将 StateFullManagedObject 的状态变量转换为 ObjStatus 以进行直接比较,这对我不起作用.例如,我不能在 Int16 和 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 不能转换为 'MirrorDisposition'

.请参阅以下条件:

var obj: StateFullManagedObject = // get the object

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

}

如何在 Int16 和枚举之间进行比较/分配?

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

推荐答案

您可以使用 ObjStatus.rawValue 属性提取原始 Int16 值.

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

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

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

但你可能想为它实现 stateEnum 访问器:

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:
    //...
}

这篇关于Swift:使用枚举在 CoreData 中存储状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:05