swiftnscodingnscoder

Encode enum with NSCoding


I am implementing NSCoding in my library, but I need to serialize an enum variable and I can't pass it in for the function that takes AnyObject?. How would this be done in Swift? Here is my enum:

enum ServerType {
  case PC
  case PE
}

Also, toRaw() and fromRaw() do not exist for ServerType. The only property I can access is hashValue, and there are no methods I can access.


Solution

  • This is similar to @Bennett's answer, but it you can use it with NSNumber as shown:

    enum ServerType: UInt {
        case PC
        case PE
    }
    
    let someType: ServerType = .PE
    NSNumber(value: someType.rawValue) // 1