首页 > 解决方案 > 根据键和值对字典数组进行排序

问题描述

最近一直在玩高阶函数,我想到了一个案例,我不知道这是否可能,考虑下面的案例。

字符串字典-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"],
]

使用高阶函数

标签: swiftdictionary

解决方案


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)

推荐阅读