gpt4 book ai didi

swift - Set 如何确保 Swift 中的等同性?

转载 作者:搜寻专家 更新时间:2023-10-31 21:59:06 24 4
gpt4 key购买 nike

我正在阅读 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 的对象也必须是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 将使用计算量更大的 == 来测试唯一性。

关于swift - Set 如何确保 Swift 中的等同性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44883930/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com