背景
我试图使用NSCoding协议编码一个字符串样式的枚举,但我遇到错误转换和返回从字符串。
解码和编码时,我得到以下错误:
字符串不能转换为Stage
额外参数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)使用toRaw()和fromRaw()像这样:
self.stage = Stage.fromRaw(aDecoder.decodeObjectForKey( "stage" ) as String) ?? .DisplayAll aCoder.encodeObject( self.stage.toRaw(),forKey:"stage" )