I'm trying to make my class conform to NSCoding
, but running into problems because one of its properties is an enum, like this:
enum Direction {
case north
case south
}
If enums were codable I could do it like this:
class MyClass: NSObject, NSCoding {
var direction: Direction!
required init(coder aDecoder: NSCoder) {
direction = aDecoder.decodeObject(forKey: "direction") as! Direction
}
func encode(with aCoder: NSCoder) {
aCoder.encode(direction, forKey: "direction")
}
}
but enums aren't codable so encode()
throws an error.
The answers to "How do I encode enum using NSCoder in swift?" suggest encoding the enum's rawValue
and then initializing it from rawValue
on the other end. But in this case, Direction
doesn't have a rawValue
!
It does have a hashValue
, which seems promising. I can encode its hashValue
without a problem, and decode back to an Int
on the other end. But there doesn't seem to be a way to initialize an enum from its hashValue
, so I can't turn it back into a Direction
.
How can I encode and decode a valueless enum?