sorted()
方法按键或值以特定顺序(升序或降序)对字典进行排序。
示例
let age = ["Ranjit": 1930, "Sabby": 2008 ]
// sort dictionary by key in ascending order
let sortAge = age.sorted(by: <)
print(sortAge)
// Output: [(key: "Ranjit", value: 1930), (key: "Sabby", value: 2008)]
sorted() 语法
字典 sorted()
方法的语法是
dictionary.sorted(by: {operator})
这里,dictionary 是 dictionary
类的一个对象。
sorted() 参数
sorted()
方法可以接受一个参数
- operator (可选) - 一个接受条件并返回 Bool 值的闭包。
注意:如果我们传递大于号运算符 >
,则字典将按降序排序
sorted() 返回值
sorted()
方法返回一个元组数组。
示例 1:Swift 字典 sorted()
var info = ["Carlos": 1999, "Nelson": 1987]
// sort dictionary by key in ascending order
let sortInfo = info.sorted(by: > )
print(sortInfo)
输出
[(key: "Nelson", value: 1987), (key: "Carlos", value: 1999)]
在这里,我们可以看到 info 字典按字符串键的升序排序。例如,"Carlos"
排在 "Nelson"
之前,因为 "C"
在 "N"
之前。
示例 2:通过传递闭包进行排序
ley info = ["Carlos": 1999, "Nelson": 1987]
// sort dictionary by value in ascending order
let sortInfo = info.sorted(by: { $0.value < $1.value } )
print(sortInfo)
输出
[(key: "Nelson", value: 1987), (key: "Carlos", value: 1999)]
在上面的示例中,我们传递了一个闭包来按值的升序对 info 进行排序。请注意闭包的定义,
{ $0.value < $1.value }
这是一个简写的闭包,用于检查 info 的第一个值是否小于第二个值。
$0
和 $1
是指传递给闭包的第一个和第二个参数的快捷方式。