检查是否符合Hashable并获取哈希值

问题描述 投票:1回答:1

我想获得符合Hashable的Any对象的哈希值。

但是,使用此代码:

    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

swift hashable
1个回答
2
投票

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

if let h = anyValue as? AnyHashable {
© www.soinside.com 2019 - 2024. All rights reserved.