在Swift中,字典的for循环不遵循其顺序

3

这是我的代码:

var keys: [String:String] = ["id": "ID", "domain": "Domain", "bundled_domain": "Bundled Domain", "dns": "DNS", "registrar": "Registrar", "registrar_url": "Registrar URL", "sponsoring_registrar": "Sponsoring Registrar", "created": "Created", "updated": "Updated", "expires": "Expires", "whois_server": "Whois Server", "status": "Status"]

for (key, name) in keys{
    println(key)
}

但结果并没有按照字典的顺序排序:

the result didn't follow order of the dictionary

那么我该如何让我的for循环按照字典的顺序进行?谢谢!

2
字典是无序的,但这个链接可能对你有所帮助:http://timekl.com/blog/2014/06/02/learning-swift-ordered-dictionaries/ - sbarow
1
for (keys, values) in yourDictionary.sorted(by: { $0.0 < $1.0 }) {...}对于(键,值)在yourDictionary.sorted(by: { $0.0 < $1.0 })中 {...} - vir us
尝试使用KeyValuePairs。https://dev59.com/DF0b5IYBdhLWcg3wGN_f - Gowrie Sammandhamoorthy
1个回答

3

来自苹果文档

Swift的字典类型没有定义顺序。要按特定顺序迭代字典的键或值,请在其键或值属性上使用全局排序函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接