Swift: 将一组字典平铺成一个字典

Swift: Flatten an array of dictionaries to one dictionary

在 Swift 中,我试图将一组字典拼合成一个字典 即

let arrayOfDictionaries = [["key1": "value1"], ["key2": "value2"], ["key3": "value3", "key4": "value4"]]


//the end result will be:   
 flattenedArray = ["key1": "value1", "key2": "value2", "key3": "value3", "key4": "value4"]

我试过使用平面图,但是返回结果的类型是[(String, AnyObject)]而不是[String, Object]

let flattenedArray = arrayOfDictionaries.flatMap { [=12=] }
// type is [(String, AnyObject)]

所以我有两个问题:

编辑:我更愿意使用 Swift 的 map/flatmap/reduce 等函数式方法,而不是 for-loop

方法如下

let arrayOfDictionaries = [["key1": "value1"], ["key2": "value2"], ["key3": "value3", "key4": "value4"]]
var dic = [String: String]()
for item in arrayOfDictionaries {
    for (kind, value) in item {
        print(kind)
        dic.updateValue(value, forKey: kind)
    }


}
print(dic)

print(dic["key1"]!)

OUTPUT

what do the brackets mean?

这个连同一个逗号而不是一个冒号,应该提供第一条线索:方括号意味着您得到一个元组数组。由于您正在寻找字典,而不是数组,这告诉您需要将元组序列(键值对)转换为单个字典。

How do I achieve the desired result?

一种方法是使用 reduce,像这样:

let flattenedDictionary = arrayOfDictionaries
    .flatMap { [=10=] }
    .reduce([String:String]()) { (var dict, tuple) in
        dict.updateValue(tuple.1, forKey: tuple.0)
        return dict
    }

正在更新@dasblinkenlight 对 Swift 3.

的回答 参数中的

"var" 已被弃用,但这种方法对我来说效果很好。

let flattenedDictionary = arrayOfDictionaries
    .flatMap { [=10=] }
    .reduce([String:String]()) { (dict, tuple) in
        var nextDict = dict
        nextDict.updateValue(tuple.1, forKey: tuple.0)
        return nextDict
    }

对于 Swift 5,Dictionay 有一个 init(_:uniquingKeysWith:) 初始值设定项。 init(_:uniquingKeysWith:) 有以下声明:

init<S>(_ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows where S : Sequence, S.Element == (Key, Value)

Creates a new dictionary from the key-value pairs in the given sequence, using a combining closure to determine the value for any duplicate keys.


以下两个 Playground 示例代码展示了如何将字典数组展平为新字典。

let dictionaryArray = [["key1": "value1"], ["key1": "value5", "key2": "value2"], ["key3": "value3"]]

let tupleArray: [(String, String)] = dictionaryArray.flatMap { [=11=] }
let dictonary = Dictionary(tupleArray, uniquingKeysWith: { (first, last) in last })

print(dictonary) // prints ["key2": "value2", "key3": "value3", "key1": "value5"]
let dictionaryArray = [["key1": 10], ["key1": 10, "key2": 2], ["key3": 3]]

let tupleArray: [(String, Int)] = dictionaryArray.flatMap { [=12=] }
let dictonary = Dictionary(tupleArray, uniquingKeysWith: { (first, last) in first + last })
//let dictonary = Dictionary(tupleArray, uniquingKeysWith: +) // also works

print(dictonary) // ["key2": 2, "key3": 3, "key1": 20]