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,就像在这篇文章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的对象也必须是Equatable.设置使用==来测试相等性,它不仅仅依赖于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只是用于唯一性的第一次测试;如果hashValues匹配,则Set将使用计算量更大的==来测试唯一性.