swift - 检查 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
解决方案
您需要使用AnyHashable
而不是,这是为解决您遇到的特定错误而创建Hashable
的协议的类型擦除版本。Hashable
if let h = anyValue as? AnyHashable {
推荐阅读
- asp.net - 有没有办法在 ASP.Net Core ReactJS 模板中构建 Web API?
- c++ - 我可以在 ANTLR4 中使用类似于 c++ 的虚拟令牌(具有相同返回值的令牌)吗?
- javascript - 如何正确执行两个球体之间的碰撞检测?
- java - 如何使用带有导航抽屉的底部导航
- python-2.7 - 在使用 Google Colab 中的所有可用 RAM 后,您的会话崩溃了
- flutter - Flutter 从 json 数组制作 GridView
- jestjs - 使用 json-server 在 Travis 上使用 Jest 模拟测试
- python-3.x - 如何检索隐藏在“点击展开”链接后面的 url 上的文本?
- javascript - 通过 HTTP Post 将动态创建的 zip 流式传输到服务器
- javascript - 函数在迭代中返回 True 而不是 False