3

I want to get the hash value of an Any object that conforms to Hashable.

However, with this code:

    let anyValue: Any
    //...
    if let h = anyValue as? Hashable {
        return h.hashValue
    }

I'm getting this error

Protocol 'Hashable' can only be used as a generic constraint because it has Self or associated type requirements

Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42
Peter Lapisu
  • 19,915
  • 16
  • 123
  • 179

1 Answers1

2

You need to use AnyHashable instead of Hashable, which is the type erased version of the Hashable protocol created to resolve that specific error you are encountering.

if let h = anyValue as? AnyHashable {
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
  • This gives me an error: `Cast from 'Error' to unrelated type 'AnyHashable' always fails` – Ky - Jan 12 '21 at 16:39
  • 1
    @BenLeggiero that's a fully separate problem. OP was using `Any`, not `Error`. Feel free to ask a new question with your different, but slightly connected problem. – Dávid Pásztor Jan 12 '21 at 16:54
  • 1
    Thanks! That actually pointed me to a solution: `(error as Any) as? AnyHashable` – Ky - Jan 12 '21 at 16:57