简体   繁体   中英

Sort dictionary of arrays by both key and values in Swift

I have a dictionary like this:

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

I would like to sort it using swift and the result should be like this:

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

Both the keys and the values in the array should be in alphabetical order. However, I can only successfully sort the keys using.keys.sorted() and I failed to sort the array in each of the dictionary values in alphabetical order.

First of all I just want to remark that it's a bit redundant to sort the keys of a dictionary because you check values associated with a given key, not where the value is, it makes no sense to order them.

Second about sorting the arrays inside the dictionary it's pretty easy, first you need to iterate over the dictionary using for each, then since the arrays are immutable after you call .sorted() you assign the result to the key associated with the value you just received.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM