在 Swift 中按键和值对数组字典进行排序

时间:2021-05-24 05:54:02

标签: ios arrays swift sorting dictionary

我有一本这样的字典:

dict = {
  "a": ["apple", "aeroplane", "ash"],
  "c": ["cat", "car"],
  "b": ["boy", "bit", "bee"]
}

我想使用 swift 对其进行排序,结果应该是这样的:

dict = {
  "a": ["aeroplane", "apple", "ash"],
  "b": ["bee", "bit", "boy"],
  "c": ["car", "cat"]
}

数组中的键和值都应按字母顺序排列。但是,我只能使用 .keys.sorted() 成功地对键进行排序,并且我未能按字母顺序对每个字典值中的数组进行排序。

1 个答案:

答案 0 :(得分:1)

首先我只想说,对字典的键进行排序有点多余,因为您检查与给定键关联的值,而不是值所在的位置,对它们进行排序是没有意义的。

第二个关于在字典中对数组进行排序非常简单,首先您需要使用 for each 遍历字典,然后由于数组在调用 .sorted() 后是不可变的,因此您将结果分配给关联的键您刚刚收到的价值。

var dict : [String:[String]] = [
  "a" : ["apple", "aeroplane", "ash"],
  "c" : ["cat", "car"],
  "b" : ["boy", "bit", "bee"]
]

// sort arrays inside an item of the dictionary
for (key,value) in dict {
    dict[key] = value.sorted()
}

print(dict)