gpt4 book ai didi

Swift 如何存储和检索集合类型

转载 作者:行者123 更新时间:2023-11-30 11:43:28 25 4
gpt4 key购买 nike

访问 Set 元素速度很快,并且 Set 类型必须是可哈希的。

我认为 Swift 只存储每个元素的散列值,但我发现原始值(未散列)也可以访问。例如这样:

var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]

for genre in favoriteGenres {
print("\(genre)")
}

输出:

// Jazz
// Hip hop
// Classical

Swift如何在内存中存储Set类型并访问它?

最佳答案

你是对的,Swift 存储的是哈希值。

All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default, and can be used as set value types or dictionary key types. Enumeration case values without associated values (as described in Enumerations) are also hashable by default.

如果您存储自己的自定义类型,它们必须符合 Hashable 协议(protocol)。

You can use your own custom types as set value types or dictionary key types by making them conform to the Hashable protocol from Swift’s standard library. Types that conform to the Hashable protocol must provide a gettable Int property called hashValue.[...]

参见https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html -> 集

在文档中,我无法找到它们存储集合类型的确切方式,但据我了解它们访问哈希值的集合

关于Swift 如何存储和检索集合类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49082974/

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