如何在swift中使用NSCoder编码枚举?

时间:2014-10-12 15:16:37

标签: swift enums persistence nscoder

背景

我正在尝试使用NSCoding协议对String样式的枚举进行编码,但是我遇到了从String转换回来的错误。

解码和编码时出现以下错误:

字符串无法转换为舞台

额外参数ForKey:在电话中

代码

    enum Stage : String
    {
        case DisplayAll    = "Display All"
        case HideQuarter   = "Hide Quarter"
        case HideHalf      = "Hide Half"
        case HideTwoThirds = "Hide Two Thirds"
        case HideAll       = "Hide All"
    }

    class AppState : NSCoding, NSObject
    {
        var idx   = 0
        var stage = Stage.DisplayAll

        override init() {}

        required init(coder aDecoder: NSCoder) {
            self.idx   = aDecoder.decodeIntegerForKey( "idx"   )
            self.stage = aDecoder.decodeObjectForKey(  "stage" ) as String    // ERROR
        }

        func encodeWithCoder(aCoder: NSCoder) {
            aCoder.encodeInteger( self.idx,             forKey:"idx"   )
            aCoder.encodeObject(  self.stage as String, forKey:"stage" )  // ERROR
        }

    // ...

    }

3 个答案:

答案 0 :(得分:65)

您需要将枚举转换为原始值或从原始值转换。在Swift 1.2(Xcode 6.3)中,这看起来像这样:

class AppState : NSObject, NSCoding
{
    var idx   = 0
    var stage = Stage.DisplayAll

    override init() {}

    required init(coder aDecoder: NSCoder) {
        self.idx   = aDecoder.decodeIntegerForKey( "idx" )
        self.stage = Stage(rawValue: (aDecoder.decodeObjectForKey( "stage" ) as! String)) ?? .DisplayAll
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeInteger( self.idx, forKey:"idx" )
        aCoder.encodeObject(  self.stage.rawValue, forKey:"stage" )
    }

    // ...

}

Swift 1.1(Xcode 6.1),使用as代替as!

    self.stage = Stage(rawValue: (aDecoder.decodeObjectForKey( "stage" ) as String)) ?? .DisplayAll

Swift 1.0(Xcode 6.0)使用toRaw()fromRaw(),如下所示:

    self.stage = Stage.fromRaw(aDecoder.decodeObjectForKey( "stage" ) as String) ?? .DisplayAll

    aCoder.encodeObject( self.stage.toRaw(), forKey:"stage" )

答案 1 :(得分:9)

更新Xcode 6.3,Swift 1.2:

self.stage = Stage(rawValue: aDecoder.decodeObjectForKey("stage") as! String) ?? .DisplayAll

请注意as!

答案 2 :(得分:6)

这是 Swift 4.2 的解决方案。如其他答案中所述,问题在于您尝试直接为stage变量分配解码后的字符串,然后尝试将stage变量强制转换为encodeWithCoder中的字符串方法。您需要改用原始值

enum Stage: String {
    case DisplayAll = "Display All"
    case HideQuarter = "Hide Quarter"
    case HideHalf = "Hide Half"
    case HideTwoThirds = "Hide Two Thirds"
    case HideAll = "Hide All"
}

class AppState: NSCoding, NSObject {
    var idx = 0
    var stage = Stage.DisplayAll

    override init() {}

    required init(coder aDecoder: NSCoder) {
        self.idx = aDecoder.decodeInteger(forKey: "idx")
        self.stage = Stage(rawValue: aDecoder.decodeObject(forKey: "stage") as String)
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encode(self.idx, forKey:"idx")
        aCoder.encode(self.stage.rawValue, forKey:"stage")
    }

    // ...

}