元类型(.Type)可以用作字典中的键吗?

Can metatype (.Type) be used as Key in Dictionary?

我有这样的东西:

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 编辑那里得到这个实时错误:

Type 'AnyObject.Type' does not conform to protocol 'Hashable'

如何使用 size 完成我想做的事情?也就是说,如何创建将类型链接到其特定大小的字典的字典?

我认为 ObjectIdentifier 会帮助我,因为它是 Hashable,但我不知道如何使用它,或者它是否是正确的选择。

HashableObjectIdentifier 实现的协议。这意味着 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”,但我不确定它是否满足您的特定需求。就个人而言,我只会使用 class 名称的字符串版本作为键 - String(Lumber)。即:

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?")