user965972 user965972 - 1 year ago 141
Swift Question

nested enum as dictionary key

Is there a reason why this doesn't work? Note: an enum as dictionary key works if it is not nested.

struct OuterStruct
enum InnerEnum
case none
case a
case b

var dict : [OuterStruct.InnerEnum: String] = [OuterStruct.InnerEnum: String]()

Answer Source

You can fix that by using the traditional way to instantiate a dictionary:

var dict : [OuterStruct.InnerEnum: String] = Dictionary<OuterStruct.InnerEnum, String>()

Note that you can use type inference and avoid specifying the variable type:

var dict = Dictionary<OuterStruct.InnerEnum, String>()

As to why the shorthand syntax doesn't work, I don't have an answer - I think you should file a radar about that. I tried turning InnerEnum into a struct and a class, and the same error is reported.

Edit For Swift 3 and above, try the following:

var dict : [OuterStruct.InnerEnum: String] = Dictionary()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download