Set 如何确保 Swift 中的等式性?

How does Set ensure equatability in Swift?

我正在阅读Set

You use a set instead of an array when you need to test efficiently for membership and you aren’t concerned with the order of the elements in the collection, or when you need to ensure that each element appears only once in a collection.

基本上Set保证了唯一性,有一些方法依赖Hashable

Use the contains(_:) method to test whether a set contains a specific element.

Use the subtracting(_:) method to create a new set with the elements of a set that are not also in another set or sequence

但是 2 个不同的对象可以具有相同的 hashValue,例如 post Swift Hashable

Do not assume that two instances of a type with the same hash value are equal. Depending on how we compute the hash value we can get collisions where two different instances share the same hash value. The Hashable protocol only needs the reverse - two equal instances have the same hash value.

那么如果2个对象有相同的hashValue,而Set只保存了1个,那么我们就有问题了?

符合Hashable的对象也必须是EquatableSet 使用 == 来测试相等性,它不仅仅依赖于 hashValue.

来自 Apple 关于 Hashable 的文档:

Conforming to the Hashable Protocol

To use your own custom type in a set or as the key type of a dictionary, add Hashable conformance to your type by providing a hashValue property. The Hashable protocol inherits from the Equatable protocol, so you must also add an equal-to operator (==) function for your custom type.

文档接着说:

Set and dictionary performance depends on hash values that minimize collisions for their associated element and key types, respectively.

因此,hashValue 只是用于唯一性的第一个测试;如果 hashValue 匹配,则 Set 将使用计算量更大的 == 来测试唯一性。