Search code examples
swiftenumsprotocols

Type 'Self' does not conform to protocol 'Hashable'


I'm struggling with error message of "Type 'Self' does not conform to protocol 'Hashable' " when using an extension to implement a type method for all conforming enums as below:

protocol A { 
    static func doSth(with dict[Self: Any])
}

extension A where Self: RawRepresentable, Self.RawValue == Int {
    static func doSth(with dict[Self: Any]) { 
       for (key, value) in dict { //...do something
       }
}

enum First: Int, A {
   case f1, f2, f3
}

enum Second: Int, A {
    case s1, s2, s3
}

....

On the other hand, when I implement the method without using protocol and extension in each of the Enums by coding my method parameter's array key type as Enum like this:

static func doSth(with dict[First: Any]) 
static func doSth(with dict[Second: Any])

and so on...I have no error and can use the method of doSth correctly. However, I have dozens of such Enums and of course prefer to implement this method in extension instead.

P.S. The purpose of the implementation is to call the method doSth with dictionary argument having a key from the enum's case, such as:

First.doSth(with: [.f1: "good", .f2:"better"]

Any suggestion is welcome.


Solution

  • Make your protocol conform to Hashable (this is precisely what the error message is saying):

    protocol A: Hashable { ...} 
    

    Your problem is that [Self: Any] isn't valid unless Self: Hashable, so your doSth method can't be defined.