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

前端 未结 1 534
情书的邮戳
情书的邮戳 2021-01-26 20:23

I have the following code:

struct TestStruct2 {
    let field1: String
    let field2: Int

    enum TestEnum2 {
        case Value1
        case Value2
    }

}         


        
1条回答
  •  北海茫月
    2021-01-26 20:42

    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()
    

    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]
    

    0 讨论(0)
提交回复
热议问题