3

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?

Nikita Zernov
  • 5,465
  • 6
  • 39
  • 70

1 Answers1

6

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382