首页 > 解决方案 > 检查 Any 是否符合 Hashable 并获取哈希值

问题描述

我想得到一个Any符合 Hashable 的对象的哈希值。

但是,使用此代码:

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

我收到此错误

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

标签: swifthashable

解决方案


您需要使用AnyHashable而不是,这是为解决您遇到的特定错误而创建Hashable的协议的类型擦除版本。Hashable

if let h = anyValue as? AnyHashable {

推荐阅读