如何在Swift中排序字典键? [英] How Are Dictionary Keys Sorted In Swift?

查看:420
本文介绍了如何在Swift中排序字典键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

检查以下字典:

var testDict: [String : Int] = [
    "a" : 1,
    "b" : 2,
    "c" : 3,
    "d" : 4
]

现在,遍历字典的键:

for i in testDict.keys {
    print(i)
}

以下输出:


bacd

b a c d

但是,预期的输出将是编码顺序的关键:

However, the expected output would be the keys in the coded order:


abcd

a b c d

由于不是这种情况,我假设按键进行排序。如果是这样,他们如何排序,更重要的是如何将它们归还给他们写的顺序?

As this is not the case, I assume that the keys are sorted. If so, how are they sorted, and more importantly, how can they be returned to the order in which they were written?

推荐答案

Apple的文档


与数组中的项目不同,字典中的项目没有
指定的顺序

Unlike items in an array, items in a dictionary do not have a specified order

简而言之,字典项目没有排序,它们通过hashValue尽可能高效地存储(您不应该对订单做出任何假设),这就是为什么:

In short, dictionary items are not sorted, they are stored as efficiently as possible by their hashValue (you should not make any assumptions over the order), that's why:


字典键类型必须符合Hashable协议,像
集的值类型。

A dictionary Key type must conform to the Hashable protocol, like a set’s value type.

对于您的第二个问题,由于字典没有排序,您不能将值或键返回到原始顺序(因为它没有任何)。您可以做的是以特定顺序迭代所有值和键,如下所示:

To your second question, since a dictionary is not sorted, you cannot return the values or keys inside to the original order (since it didn't have any). What you can do is iterate through all values and keys in a specific order, like this:

let dic = ["a" : 1, "b" : 2, "c" : 3, "d" : 4]
for key in dic.keys.sort(<) {
    print("key: \(key), value: \(dic[key])")
}

这篇关于如何在Swift中排序字典键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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