Swift: How to encode a hash map with enum as the key?

2k views Asked by At

I have enum like this:

   enum Direction : String {
      case EAST  = "east"
      case SOUTH = "south"
      case WEST  = "west"
      case NORTH = "north"
    }

And I have a variable called result which is a Hashmap using these enum direction as the key.

var result = [Direction:[String]]()

I tried to encode this object and send to the other side through the multipeer framework. However, it fails at the encoder.

aCoder.encode(self.result, forKey: "result")

Error says that: "encode(with aCoder: NSCoder) *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance 0x17045f230'

How can I encode this Hashmap?

Thanks.

1

There are 1 answers

2
OOPer On BEST ANSWER

As noted in JAL's comment NSCoding feature is based on Objective-C runtime, so you need to convert your Dictionary to something which is safely convertible to NSDictionary.

For example:

func encode(with aCoder: NSCoder) {
    var nsResult: [String: [String]] = [:]
    for (key, value) in result {
        nsResult[key.rawValue] = value
    }
    aCoder.encode(nsResult, forKey: "result")
    //...
}
required init?(coder aDecoder: NSCoder) {
    let nsResult = aDecoder.decodeObject(forKey: "result") as! [String: [String]]
    self.result = [:]
    for (nsKey, value) in nsResult {
        self.result[Direction(rawValue: nsKey)!] = value
    }
    //...
}