Erik Erik - 2 years ago 319
Swift Question

Conforming an array of enums to Hashable for use as dictionary key

I'd like to use an array of custom enums as a dictionary key, but I'm having difficulty figuring out how to make the array conform to Hashable. The compiler tells me that [Symbol] doesn't conform to Hashable. What do I have to do to get this to compile?

I messed around with an extension to Array where Element:Symbol, but I couldn't figure out how to add a protocol that way.

enum Symbol:Hashable, Equatable {
case Dot
case Dash

var value:Int {
get {
switch self {
case .Dot: return 0
case .Dash: return 1

var hashValue:Int {
return self.value

func ==(left: Symbol, right: Symbol) -> Bool {
return left.value == right.value

struct MorseDictionary {
static let symbolToStringDictionary:[[Symbol]:String] = [
[.Dot, .Dash]:"A"

Answer Source

In Swift 2.2 you cannot create an extension restricted to an Array of a specific type

So you cannot conform an Array of Symbol to Hashable or Equatable. This means you cannot use an Array of Symbol as key in a Dictionary.

Of course you can create an extension making Array (every array!!) Equatable and Hashable but it's a crazy approach since obviously you will never be able to provide a valid implementation.

However you can follow another approach

First of all your enum can be rewritten this way

enum Symbol: Int {
    case Dot = 0, Dash

Next you'll need a wrapper for an array of Symbol

struct Symbols: Hashable, Equatable {
    let value: [Symbol]

    // you can use a better logic here
    var hashValue: Int { return value.first?.hashValue ?? 0 }

func ==(left: Symbols, right:Symbols) -> Bool {
    return !zip(left.value, right.value).contains { $0.0 != $0.1 }

Now you can create your dictionary

let dict: [Symbols:String] = [Symbols(value: [.Dot, .Dash]) : "A"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download