Swift字典排序 [英] Swift dictionary sorting

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

问题描述

我只是想知道字典在Swift中是如何排序的.例如以下代码.

just wondered how dictionary sorts in Swift. e.g. the following code.

var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic"]

occupations["Jayne"] = "Pirate"

for (name, occupation) in occupations{
print("\(name) is a \(occupation)")
}

结果看起来像这样

Kaylee is a Mechanic 
Malcolm is a Captain
Jayne is a Pirate

我的问题仍然存在.循环如何决定在上述循环中首先传递哪个名称(或键)?

My question stands. How does the cycle decide which name(or a key) will be first passed through the above cycle?

推荐答案

来自Apple 集合类型文档:

字典存储相同类型的键和之间的关联 集合中相同类型的值,没有定义的顺序.每个 值与唯一键相关联,该唯一键用作以下内容的标识符 字典中的那个值. 不同于数组中的项目,中的项目 字典不是没有指定的顺序.

A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering. Each value is associated with a unique key, which acts as an identifier for that value within the dictionary. Unlike items in an array, items in a dictionary do not have a specified order.

默认情况下,字典数据结构具有未指定的顺序,这意味着每次进行迭代时,您可能会有不同的排序.但是,您可以基于键的 values 进行排序,它们都表示为数组.

By default, dictionary data structure has unspecified ordering, means that each time you will iterate through it you might have a different sorting. However you can sort based on the keys or the values of it, both of them are represented as arrays.

因此,假设您要根据键进行排序:

So, let's say that you want to sort based on the keys:

    var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic"]

occupations["Jayne"] = "Pirate"

for key in occupations.keys.sort() {
    print("KEY: \(key) VALUE: \(occupations[key])")
}

控制台应显示-根据键排序-:

Console should shows -sorted based on the key-:

KEY :Jayne VALUE :可选(海盗")

KEY: Jayne VALUE: Optional("Pirate")

KEY :Kaylee VALUE :可选(机械")

KEY: Kaylee VALUE: Optional("Mechanic")

KEY :马尔科姆 VALUE :可选(队长")

KEY: Malcolm VALUE: Optional("Captain")

请注意,这些值是可选的,您可能需要可选绑定"它们...

希望这会有所帮助.

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

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