gpt4 book ai didi

SwiftUI 符合 Hashable

转载 作者:行者123 更新时间:2023-12-03 17:12:40 33 4
gpt4 key购买 nike

我们如何让 SwiftUI 对象,尤其是 Image,符合 Hashable 协议(protocol)?

我知道它们符合 Equatable 协议(protocol),所以主要问题是如何获取哈希值,或者使用 hash(into:)功能?

最佳答案

In Swift, conforming to the Hashable protocol is often just as easy as adding Hashable to your conformance list. However, if you have custom requirements, or use properties that don’t all conform to Hashable, it takes a little more work.



这是我们可以使用的示例结构:
struct iPad: Hashable {
var serialNumber: String
var capacity: Int
}

Because that conforms to the Hashable protocol and both its properties also conform to the Hashable protocol, Swift will generate a hash(into:) method automatically.

However, in this case we can see that serialNumber is enough to identify each iPad uniquely so hashing capacity isn’t needed. So, we can write our own implementation of hash(into:) that hashes just that one property:


func hash(into hasher: inout Hasher) {
hasher.combine(serialNumber)
}

You can add more properties to your hash by calling combine() repeatedly, and the order in which you add properties affects the finished hash value.



Swift 每次对对象进行哈希处理时都会使用随机种子,这意味着任何对象的哈希值都可以有效地保证在您的应用程序运行之间是不同的。

这反过来意味着您添加到集合或字典中的元素很可能在您每次运行应用程序时具有不同的顺序。

来源: https://www.hackingwithswift.com/example-code/language/how-to-conform-to-the-hashable-protocol

This也可能有帮助。

关于SwiftUI 符合 Hashable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59383220/

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