Search code examples
iosswiftnscoder

Encode and Decode enum in Swift 1.2


I have a enum in my Swift class and a variable declared. I need to encode and decode it using NSCoder. There are a lot of questions about this saying that I should use rawValue. Enum is declared the following way:

enum ConnectionType {
    case Digital, PWM
}

But in Swift 1.2 there is no such initialiser. How do do that in Swift 1.2 and Xcode 6.3?


Solution

  • You have to define a "raw type" for the enum, e.g.

    enum ConnectionType : Int {
        case Digital, PWM
    }
    

    Then you can encode it with

    aCoder.encodeInteger(type.rawValue, forKey: "type")
    

    and decode with

    type = ConnectionType(rawValue: aDecoder.decodeIntegerForKey("type")) ?? .Digital
    

    where the nil-coalescing operator ?? is used to supply a default value if the decoded integer is not valid for the enumeration.