Search code examples
swifthashable

Check if Any conforms to Hashable and get hash value


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


Solution

  • 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 {