Swift: 如何对以枚举为键的哈希映射进行编码?

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

我有这样的枚举:

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

我有一个名为 result 的变量,它是一个使用这些枚举方向作为键的 Hashmap。

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

我尝试对这个对象进行编码并通过multipeer框架发送给另一端。但是,它在编码器上失败了。

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

错误说: “编码(使用编码器:NSCoder) *** 由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'-[_SwiftValue encodeWithCoder:]:无法识别的选择器发送到实例 0x17045f230'

如何编码这个 Hashmap?

谢谢。

如 JAL 的评论所述 NSCoding 功能基于 Objective-C 运行时,因此您需要将字典转换为可安全转换为 NSDictionary.[=13= 的内容]

例如:

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
    }
    //...
}