Encode and decode enum in Swift 1.2
I have enum
in my Swift class and a variable declared. I need to encode and decode it with NSCoder
. There are many questions about this application that I should be using rawValue
. enum
is declared like this:
enum ConnectionType {
case Digital, PWM
}
But Swift 1.2 doesn't have such an initializer. How do I do this in Swift 1.2 and Xcode 6.3?
+3
source to share
1 answer
You must define a "raw type" for the enum, for example
enum ConnectionType : Int {
case Digital, PWM
}
Then you can code 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 set the default if the decoded integer is not valid for the enumeration.
+6
source to share