Swift:如何使用枚举作为密钥对哈希映射进行编码?
我有枚举这样的:Swift:如何使用枚举作为密钥对哈希映射进行编码?
enum Direction : String {
case EAST = "east"
case SOUTH = "south"
case WEST = "west"
case NORTH = "north"
}
和我有一个变量被称为结果是使用这些枚举方向为关键一个HashMap中。
var result = [Direction:[String]]()
我试着对这个对象进行编码并通过multipeer框架发送给对方。但是,它在编码器上失败。
aCoder.encode(self.result, forKey: "result")
错误说: “编码(与aCoder:NSCoder) ***终止应用程序由于未捕获的异常 'NSInvalidArgumentException',原因是:“ - [_ SwiftValue encodeWithCoder:]:无法识别的选择发送到实例0x17045f230 “
我怎么能编码此HashMap?
感谢。
作为日航的评论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
}
//...
}
如果我的设置是这样的结构: [AnotherEnumType:[方向:[字符串]]] 为什么我没有写 VAR nsResult:[字符串:字符串:[平铺]]] = [:[: [Tile]]] – user6539552
@ user6539552,请编辑您的问题并显示更具体的例子,指定如何定义AnotherEnumType和Tile。 – OOPer
谢谢,它解决了我的问题! – user6539552
请注意,这是使用'lowerCamelCase',枚举案件斯威夫特约定(这不是Java!)。我还假设你在说Hashmap时指的是'Dictionary'。另外'var result = [Direction [String]]'是无效的Swift,你的意思是'var result = [Direction:[String]]()'或'var result:[Direction:[String]]'? – Hamish
这是一篇重复的文章。 http://*.com/questions/24562357/how-can-i-use-a-swift-enum-as-a-dictionary-key-conforming-to-equatable – mrabins
是的,我的意思是var result = [Direction: [String]]() – user6539552