How to encode an enumeration using NSCoder in swift?

Background

I am trying to encode a String-style enumeration using the NSCoding protocol, but I am triggering errors that convert to String and vice versa.

When decoding and encoding, I get the following errors:

String cannot be converted to Stage

ForKey optional argument: when invoked

the code

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 } // ... } 
+49
enums swift persistence nscoder
Oct 12 '14 at 15:16
source share
2 answers

You need to convert the enumeration to and from the original value. In Swift 1.2 (Xcode 6.3), it will look like this:

 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) uses as instead of as! :

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

Swift 1.0 (Xcode 6.0) uses toRaw() and fromRaw() as follows:

  self.stage = Stage.fromRaw(aDecoder.decodeObjectForKey( "stage" ) as String) ?? .DisplayAll aCoder.encodeObject( self.stage.toRaw(), forKey:"stage" ) 
+53
Oct 12 '14 at 15:26
source share

Update for Xcode 6.3, Swift 1.2:

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

pay attention to as!

+8
Mar 10 '15 at 13:10
source share



All Articles