Check if Any conforms to Hashable and get hash value

Viewed 390

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

1 Answers

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