0

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.

Bennett
  • 1,007
  • 4
  • 15
  • 29

2 Answers2

3

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
Coder-256
  • 5,212
  • 2
  • 23
  • 51
  • Would also work, but I just noticed that for my code there is a case where it should be string. – Bennett Dec 24 '16 at 17:29
  • Yes, but I also included this because it has some advantages. Your solution allows for reordering but not renaming the cases, but mine allows for renaming but not reordering the cases which I think is more useful. You can use either answer, just be sure to mark one of them as correct if it works. – Coder-256 Dec 24 '16 at 17:32
  • Yeah, but I'm changing a path like `https://example.com/` to `https://example.com/pc` or `https://example.com/pe` depending on the value. If it's a string, I can just say `case PC = "pc"` and `case PE = "pe"` and then use `https://example.com/\(serverValue.rawValue)"`. In an ambiguous case, this would work and have advantages. – Bennett Dec 24 '16 at 17:35
  • @Bennett You still can. Just do: `"https://example.com/\(someType)"` or, in your case, `"https://example.com/\(serverValue)"` – Coder-256 Dec 24 '16 at 17:37
  • But then it would be `https://example.com/1` (if `serverValue = .PE`) instead of `https://example.com/pe` – Bennett Dec 24 '16 at 17:40
  • @Bennett Strange, both of these worked just fine in my testing: `let url = "https://example.com/\(someType)"` or `let url = "https://example.com/\(ServerType.PE)"`. – Coder-256 Dec 24 '16 at 17:42
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/131420/discussion-between-bennett-and-coder256). – Bennett Dec 24 '16 at 17:43
0

Change your code to

enum ServerType : String {
  case PC
  case PE
}

and you should be able to use the rawValue parameter.

Bennett
  • 1,007
  • 4
  • 15
  • 29