我有这样的枚举:
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")
错误说: “编码(使用aCoder:NSCoder) *** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[_SwiftValueencodeWithCoder:]:无法识别的选择器发送到实例 0x17045f230”
如何编码这个 HashMap ?
谢谢。
最佳答案
正如 JAL 评论中所述,NSCoding
功能基于 Objective-C 运行时,因此您需要将字典转换为可安全转换为 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
}
//...
}
关于ios - Swift:如何以枚举为键对 HashMap 进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41367796/