我有以下字典:
let dict = ["key1": "v1", "key2": "v1", "key3": "v2"]
我想交换键的值,以便结果为:
result = ["v1": ["key1", "key2"], "v2": ["key3"]]
如果不使用for
循环(即更优雅),我怎么能这样做?
您可以在Swift 4中使用分组初始化程序:
let dict = ["key1": "v1", "key2": "v1", "key3": "v2"]
let result = Dictionary(grouping: dict.keys.sorted(), by: { dict[$0]! })
两个笔记:
.sorted()
。$0
参数在Swift 4中,Dictionary
有init(_:uniquingKeysWith:)
初始化程序,应该在这里很好用。
let d = [1 : "one", 2 : "two", 3 : "three", 30: "three"]
let e = Dictionary(d.map({ ($1, [$0]) }), uniquingKeysWith: {
(old, new) in old + new
})
如果原始字典中没有需要组合的重复值,这将更简单(使用another new initializer):
let d = [1 : "one", 2 : "two", 3 : "three"]
let e = Dictionary(uniqueKeysWithValues: d.map({ ($1, $0) }))