根据键和值对字典数组进行排序

时间:2019-02-18 10:25:44

标签: swift dictionary

最近在high order functions周围玩耍, 我想到了一个案例,我不知道这是否有可能, 请考虑以下情况。

  

StringDictionary -typealias StringDictionary = [String: String]

var Group: [StringDictionary] =  [
["Key1":"val2"],
["Key4":"val4"],
["Key3":"val3"],
["Key5":"val5"],
["Key2":"val1"],
]

我想对这组字典重新排序,就像这样。
预期结果

 var Result =  [
    ["Key1":"val1"],
    ["Key2":"val2"],
    ["Key3":"val3"],
    ["Key4":"val4"],
    ["Key5":"val5"],
]

使用高级功能

1 个答案:

答案 0 :(得分:2)

typealias StringDictionary = [String: String]

var Group: [StringDictionary] =  [
    ["Key1":"val2"],
    ["Key4":"val4"],
    ["Key3":"val3"],
    ["Key5":"val5"],
    ["Key2":"val1"],
]
let keys = Group.map { Array($0.keys) }.reduce([String]()) { $0 + $1 }.sorted()
let values = Group.map { Array($0.values) }.reduce([String]()) { $0 + $1 }.sorted()
let dict = Dictionary(uniqueKeysWithValues: zip(keys, values))
let newGroup:[StringDictionary] = dict.map { [$0:$1] }.sorted{ $0.keys.first! < $1.keys.first! }
print(newGroup)