我如何使用NSCoder快速编码枚举?

背景

我想使用NSCoding协议编码一个string样式的枚举,但我正在运行到转换为和返回从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 } // ... } 

您需要将枚举值转换为原始值。 在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!

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

Swift 1.0(Xcode 6.0 fromRaw()像这样使用toRaw()fromRaw()

  self.stage = Stage.fromRaw(aDecoder.decodeObjectForKey( "stage" ) as String) ?? .DisplayAll aCoder.encodeObject( self.stage.toRaw(), forKey:"stage" ) 

更新Xcode 6.3,Swift 1.2:

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

注意as!