Encode enum with NSCoding

1.3k views Asked by At

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.

2

There are 2 answers

7
Coder-256 On BEST ANSWER

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
0
Bennett On

Change your code to

enum ServerType : String {
  case PC
  case PE
}

and you should be able to use the rawValue parameter.