我知道Hashable是继承自Equatable,但是你能举个例子,需要Hashable,而不仅仅是Equatable。谢谢!
最佳答案
您可以使用 hashValue
来确定两个对象是否不彼此相等。
除此之外,您不应该仅根据对象的哈希值对对象进行任何Equatable
或Comparable
确定。
简而言之,Hashable
派生自 Equatable
,因为您无法仅通过测试它们的 hashValue来安全地确定两个对象是否彼此相等
平等。
更多详情
根据 Swift documentation :
A hash value is an Int value that is the same for all objects that compare equally, such that if
a == b
, it follows thata.hashValue == b.hashValue
.
然而,反之则不然。如果a.hashValue == b.hashValue
,它不遵循a == b
。
虽然有返回唯一
值的完美散列函数,但散列函数可以为两个或多个不同的对象返回相同的hashValue
。这称为哈希冲突。
避免尝试这样做
For Hashable, because you can get a number that represents the object, you can kind of treat the objects as numbers. You can compare the objects: whether it is less than, greater than, or equal to another object, just like you do with numbers:
没有。您正在比较的是(可能发生碰撞的)对象的哈希值,不是对象本身。
- 比较一个哈希值是小于还是大于另一个哈希值对于对象而言是没有意义的。
- 关于相等性,如果哈希函数为对象返回了一个完全唯一的值,它才成立。
Equatable
之外,Hashable
本身的用途非常有限。为了安全起见,您应该始终测试对象本身。
关于swift - Swift 中的 Hashable 和 Equatable 有什么用?什么时候使用哪个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34915836/