10

我有这样的事情:

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 编辑器中得到了这个实时错误:

类型“AnyObject.Type”不符合协议“Hashable”

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

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

4

1 回答 1

13

Hashable是一个ObjectIdentifier实现的协议。这意味着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?")
于 2016-02-22T06:04:50.863 回答