【问题标题】:How to use enum (which is defined inside a struct) as key of dictionary?如何使用枚举(在结构中定义)作为字典的键?
【发布时间】:2017-04-21 12:28:49
【问题描述】:

我有以下代码:

struct TestStruct2 {
    let field1: String
    let field2: Int

    enum TestEnum2 {
        case Value1
        case Value2
    }

}

    let dic2 = Dictionary<TestStruct2.TestEnum2, TestStruct2>()
    let dic3 = [TestStruct2.TestEnum2 : TestStruct2]()

dic2 工作成功。

但是 dic3 返回编译器错误:

 (Type of expression is ambiguous without more context)

我不明白为什么。有什么想法吗?

【问题讨论】:

标签: swift


【解决方案1】:

正如@Hamish 在 cmets 中提到的,这是一个编译器错误。您已经展示了一种使用长格式的解决方法:

let dic2 = Dictionary<TestStruct2.TestEnum2, TestStruct2>()

第二种解决方法是为嵌套类型创建typealias

typealias TestStruct2Enum2 = TestStruct2.TestEnum2

let dic3 = [TestStruct2Enum2 : TestStruct2]()

第三种解决方法是创建整个字典的typealias

typealias Test2Dict = [TestStruct2.TestEnum2 : TestStruct2]

let dic4 = Test2Dict()

第四个解决方法是显式指定类型并使用 [:] 字面量初始化字典:

let dic5: [TestStruct2.TestEnum2 : TestStruct2] = [:]

最后的解决方法是将文字转换为类型:

let dic6 = [:] as [TestStruct2.TestEnum2 : TestStruct2]

【讨论】:

    猜你喜欢
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 2014-08-25
    • 2011-08-10
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    相关资源
    最近更新 更多