Swift 基于键和值对字典数组进行排序
最近一直在玩游戏, 我想到了一个案子我不知道这是否可能, 考虑下面的例子。 StringDictionary-Swift 基于键和值对字典数组进行排序,swift,dictionary,Swift,Dictionary,最近一直在玩游戏, 我想到了一个案子我不知道这是否可能, 考虑下面的例子。 StringDictionary-typealias StringDictionary=[String:String] 我想将此字典数组重新排序为如下所示。 预期结果 var Result = [ ["Key1":"val1"], ["Key2":"val2"], ["Key3":"val3"], ["Key4":"val4"], ["Key5":"val5"], ] 使用高
typealias StringDictionary=[String:String]
我想将此字典数组重新排序为如下所示。预期结果
var Result = [
["Key1":"val1"],
["Key2":"val2"],
["Key3":"val3"],
["Key4":"val4"],
["Key5":"val5"],
]
使用高阶函数typealias StringDictionary=[String:String]
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)
变量组:[StringDictionary]=[
[“Key1”:“val2”],
[“Key4”:“val4”],
[“Key3”:“val3”],
[“键5”:“值5”],
[“键2”:“值1”],
]
让keys=Group.map{Array($0.keys)}.reduce([String]()){$0+$1}.sorted()
让values=Group.map{Array($0.values)}.reduce([String]()){$0+$1}.sorted()
让dict=Dictionary(uniqueKeysWithValues:zip(键,值))
让newGroup:[StringDictionary]=dict.map{[$0:$1]}。排序{$0.keys.first!<$1.keys.first!}
打印(新组)
您可以对键进行排序,然后将其用作以排序方式访问词典的一种方式。是的意思是一个词典数组:)为什么它是一个词典数组而不是一个词典?检查更新的答案,但如果再次使用排序,则会丢失第一个排序:)您的答案是正确的检查预期结果,添加以前使用键删除的排序功能values@MohmmadS您想同时对键和值进行排序吗?是的,请检查问题,这里我们丢失了键顺序。。。这是我忘记排序的扭曲
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)