Confused
Confused

Reputation: 3926

How can I pass enum objects as a dictionary key in Swift?

I have two simple enums like:

enum A: String {
    case i = "i"
    case j = "j"
}

enum B: String {
    case x = "x"
    case y = "y"
    case i = "i"
}

And, I have a dictionary which maps all enum values with some other values.

var myDict:[String:String] = [
    A.i.rawValue : "i in A",
    A.j.rawValue : "j in A",
    B.x.rawValue : "x in B",
    B.y.rawValue : "y in B",
    B.i.rawValue : "i in B"
]

Running this code throws an error:

Fatal error: Dictionary literal contains duplicate keys

Because a dictionary can not hold same multiple keys in it.

Question:

Is it possible to pass enum objects instead of their raw values? Something like this:

var myDict:[<Dont know what to type here>:String] = [
    A.i: "i in A",
    A.j: "j in A",
    B.x: "x in B",
    B.y: "y in B",
    B.i: "i in B"
]

Help needed!

Upvotes: 0

Views: 2320

Answers (1)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

You need the key to be of type AnyHashable.

var myDict:[AnyHashable: String] = [
    A.i: "i in A",
    A.j: "j in A",
    B.x: "x in B",
    B.y: "y in B",
    B.i: "i in B"
]

print(myDict[A.i] ?? "") // "i in A"
print(myDict[B.i] ?? "") // "i in B"

The basic requirement for a dictionary key is that it conforms the protocol Hashable, and enum conforms to it.

Upvotes: 4

Related Questions