2016-11-25 50 views
1

我有以下代码:如何使用枚举(在结构中定义)作为字典的关键?

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) 

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

+3

这是编译器故障,见[为什么不能实例化一个嵌套类的空数组? ](http://stackoverflow.com/questions/25682113/why-cant-i-instantiate-an-empty-array-of-a-nested-class)你也可以使用嵌套类型的'typealias'来工作周围。 – Hamish

回答

1

正如@Hamish在评论中提到的那样,这是一个编译器错误。你已经展示了一个解决方法是使用长形式:

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]