我有这样的事情:
class Lumber { }
class Fruit { }
enum Size {
case small
case medium
case large
}
let lumberSize = [
Size.small: "2x4",
Size.medium: "4x6",
Size.large: "6x10"
]
let fruitSize = [
Size.small: "grape",
Size.medium: "apple",
Size.large: "watermelon"
]
let size:[AnyObject.Type:Dictionary] = [
Lumber.Type: lumberSize,
Fruit.Type: fruitSize
]
在我的
size
字典定义中,我从Xcode编辑器得到了这个实时错误:如何完成对
size
的尝试?也就是说,如何创建将类型链接到其特定大小字典的字典?我认为
ObjectIdentifier
可以帮助我,因为它是Hashable
,但我不知道如何使用它,或者它是否是正确的选择。 最佳答案
Hashable
是ObjectIdentifier
实现的协议(protocol)。这意味着ObjectIdentifier(Lumber.Type)
是可哈希的,而不是Lumber.Type
是可哈希的。您可以尝试将代码更改为使用ObjectIdentifier,如下所示:
class Lumber { }
class Fruit { }
enum Size {
case small
case medium
case large
}
let lumberSize = [
Size.small: "2x4",
Size.medium: "4x6",
Size.large: "6x10"
]
let fruitSize = [
Size.small: "grape",
Size.medium: "apple",
Size.large: "watermelon"
]
let size:[ObjectIdentifier:[Size:String]] = [
ObjectIdentifier(Lumber.self): lumberSize,
ObjectIdentifier(Fruit.self): fruitSize
]
let t = size[ObjectIdentifier(Lumber.self)]
let s = t?[.small]
print(s ?? "no s?")
这将编译并打印“2x4”,但是我不确定它是否满足您的特定需求。就个人而言,我只是将类名的字符串版本用作键
String(Lumber)
。 IE。:let size:[String:[Size:String]] = [
String(describing:Lumber.self): lumberSize,
String(describing:Fruit.self): fruitSize
]
let t = size[String(describing:Lumber.self)]
let s = t?[.small]
print(s ?? "no s?")