swift - Swift 中的 Hashable 和 Equatable 有什么用?什么时候使用哪个?

标签 swift

我知道Hashable是继承自Equatable,但是你能举个例子,需要Hashable,而不仅仅是Equatable。谢谢!

最佳答案

您可以使用 hashValue 来确定两个对象是否彼此相等。

除此之外,您不应该仅根据对象的哈希值对对象进行任何EquatableComparable 确定。

简而言之,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 that a.hashValue == b.hashValue.

然而,反之则不然。如果a.hashValue == b.hashValue,它遵循a == b

虽然有返回唯一值的完美散列函数,但散列函数可以为两个或多个不同的对象返回相同的hashValue。这称为哈希冲突

避免尝试这样做

Sweeper's answer说:

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/

相关文章:

json - 类型 'AreaData' 不符合协议(protocol) 'Encodable'

ios - Apple Watch 无法将数据传递至 iPhone - Swift

swift - 如何在运行序列之前等待一段时间?

ios - 设置 WKInterfacePicker 颜色(文本或轮廓)

swift - 如何停止后台更新任务?

ios - <<和>>在swift中是什么意思

swift - 如何扁平化 AnyPublisher<AnyPublisher<>>?

ios - ParseTwitterUtils 内部服务器错误

objective-c - 多个类使用委托(delegate)的设计模式

swift - 第一次使用 Xcode 7 时,我收到了一个额外的参数错误调用,代码如下 -