Set如何确保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,就像在这文章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将使用计算量更大的==来测试唯一性.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...