How does Set ensure equatability in Swift?

亡梦爱人 提交于 2019-12-23 22:45:12

问题


I'm reading 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.

Basically Set ensures uniqueness, it has some methods and relies on 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

But 2 different objects can have the same hashValue, like in this 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.

So what if 2 objects have the same hashValue, and Set only saves 1, then we have the problem?


回答1:


An object that conforms to Hashable must also be Equatable. Set uses == to test for equality, it doesn't depend only on the hashValue.

From Apple's documentation on 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.

The documentation goes on to say:

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

So, the hashValue is just used a first test for uniqueness; if the hashValues match then Set will use the more computationally expensive == to test for uniqueness.



来源:https://stackoverflow.com/questions/44883930/how-does-set-ensure-equatability-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!