Swift字典会自动排序吗? [英] Are Swift dictionaries automatically sorted?
问题描述
我有这两个字典:
let test = ["Tomorrow": "Bla", "Month": "Bla"]
print(test) // ["Tuesday": "Bla", "Month": "Bla"]
let test1 = ["Tomorrow": "Bla", "One Month": "Bla"]
print(test2) // ["One Month": "Bla", "Tuesday": "Bla"]
似乎,如果我使用关键字"One",该元素将放在前面.为什么?
It seems that if i use the keyword "One" the element gets placed in front. Why?
推荐答案
Swift的Dictionary
是基于哈希的数据结构.除非采用特定的排序机制,否则基于哈希的结构中项目的顺序取决于以下几个因素:
Swift's Dictionary
is a hash-based data structure. Unless a specific ordering mechanism is in place, the order of items in hash-based structures depends on several factors:
- 用作键的对象的哈希值-
hashValue
方法用于确定项目的存储桶编号 - 结构的大小-由于
hashValue
可能比可用的存储桶数大得多,因此使用了限制机制(例如模存储桶数)来确定实际的存储桶数 - 修改顺序-当按键发生碰撞时,这变得很重要.稍后将具有重复哈希值的元素放置到另一个存储桶,或放置在与实际存储桶相关联的列表中.
- Hash values of objects used as keys -
hashValue
method is used to determine the bucket number for the item - Size of the structure - Since
hashValue
can be much larger than the number of buckets available, a limiting mechanism, such as modulo bucket count, is used to decide the actual bucket number - Modification order - this becomes relevant when keys have collisions. Elements with duplicate hash value placed later would either go to a different bucket, or be placed in a list associated with the actual bucket.
例如,如果您在第二个示例中更改字典的大小,则项目的顺序将相反:
For example, if you change the size of dictionary in your second example, the order of items would reverse:
var test1 = [String:String]() // Use default initial capacity
test1["Tomorrow"] = "Bla"
test1["One Month"] = "Bla"
print(test1) // ["One Month": "Bla", "Tomorrow": "Bla"]
var test2 = [String:String](minimumCapacity: 11) // Use specific capacity
test2["Tomorrow"] = "Bla"
test2["One Month"] = "Bla"
print(test2) // ["Tomorrow": "Bla", "One Month": "Bla"]
由于其中某些参数不在您的控制范围之内,因此Dictionary
中的项目顺序对于所有实际目的都可以认为是任意的.
Since some of these parameters are outside your control, the order of items in a Dictionary
can be considered arbitrary for all practical purposes.
这篇关于Swift字典会自动排序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!