How do I encode enum using NSCoder in swift?

前端 未结 3 1167
长发绾君心
长发绾君心 2020-11-27 05:02

Background

I am trying to encode a String-style enum using the NSCoding protocol, but I am running into errors converting to and back from String.

3条回答
  •  生来不讨喜
    2020-11-27 05:56

    You need to convert the enum to and from the raw value. In Swift 1.2 (Xcode 6.3), this would 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() like this:

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

提交回复
热议问题