dschmidt dschmidt - 11 days ago 8
Swift Question

How to use enum (which is defined inside a struct) as key of dictionary?

I have the following code:

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 works successfully.

But dic3 returns an compiler error:

(Type of expression is ambiguous without more context)


I don't understand why. Any Ideas?

Answer

As mentioned by @Hamish in the comments, this is a compiler bug. You've already shown one workaround which is to use the long form:

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

A second workaround is to create a typealias for the nested type:

typealias TestStruct2Enum2 = TestStruct2.TestEnum2

let dic3 = [TestStruct2Enum2 : TestStruct2]()

A third workaround is to create a typealias of the entire dictionary:

typealias Test2Dict = [TestStruct2.TestEnum2 : TestStruct2]

let dic4 = Test2Dict()

A fourth workaround is to explicitly specify the type and initialize the dictionary with the [:] literal:

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

A final workaround is to cast the literal to the type:

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