Set 如何确保 Swift 中的平等性? [英] How does Set ensure equatability in Swift?

查看:38
本文介绍了Set 如何确保 Swift 中的平等性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读设置

当您需要有效地测试成员资格并且不关心集合中元素的顺序时,或者需要确保每个元素在集合中只出现一次时,请使用集合而不是数组.

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

Basically Set ensures uniqueness, it has some methods and relies on Hashable

使用 contains(_:) 方法测试集合是否包含特定元素.

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

But 2 different objects can have the same hashValue, like in this post Swift Hashable

不要假设具有相同哈希值的类型的两个实例是相等的.根据我们计算散列值的方式,我们可以得到两个不同实例共享相同散列值的冲突.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个,那么问题来了?

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

推荐答案

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

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

来自 Apple 关于 Hashable 的文档:

From Apple's documentation on Hashable:

符合 Hashable 协议

使用您自己的自定义类型设置或作为字典的键类型,添加 Hashable 一致性到您的类型通过提供 hashValue 属性.可哈希协议继承自 Equatable 协议,因此您还必须添加一个等于自定义类型的运算符 (==) 函数.

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 将使用计算量更大的 == 来测试唯一性.

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.

这篇关于Set 如何确保 Swift 中的平等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆