【问题标题】:Swift: How to encode a hash map with enum as the key?Swift:如何以枚举为键对哈希映射进行编码?
【发布时间】:2017-05-13 01:49:27
【问题描述】:

我有这样的枚举:

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

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

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

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

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

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

如何编码这个 Hashmap?

谢谢。

【问题讨论】:

  • 请注意,在枚举情况下使用 lowerCamelCase 是 Swift 约定(这不是 Java!)。我还假设您在说 Hashmap 时指的是Dictionaryvar result = [Direction[String]] 也不是有效的 Swift,你的意思是 var result = [Direction : [String]]() 还是 var result : [Direction : [String]]
  • 这是一篇重复的文章。 stackoverflow.com/questions/24562357/…
  • 是的,我的意思是 var result = [Direction : [String]]()
  • 这不是问题的重复。我要问的是如何序列化(编码)对象。
  • 相关:How do I encode enum using NSCoder in swift?。使用枚举的rawValue

标签: ios swift enums encode multipeer-connectivity


【解决方案1】:

正如 JAL 的评论中所述,NSCoding 功能基于 Objective-C 运行时,因此您需要将 Dictionary 转换为可安全转换为 NSDictionary 的内容。

例如:

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

【讨论】:

  • 如果我的集合是这样的结构怎么办:[AnotherEnumType: [Direction: [String]]] 为什么我写失败 var nsResult: [String: [String:[Tile]]] = [: [:[平铺]]]
  • @user6539552,请编辑您的问题并展示更具体的示例,说明如何定义 AnotherEnumTypeTile
猜你喜欢
  • 2016-12-13
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 2016-10-04
  • 2012-11-14
  • 2011-09-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多