I'm looking for an elegant way to combine an array of dictionaries.
Input: [[a: foo], [b: bar], [c: baz]]
Output: [a: foo, b: bar, c: baz]
What's the best way to achieve this?
You could use reduce but you'd have to define a "combine" method that would give you a combined dictionary from 2 individual dictionaries.
So you could do something like this
let inputArray = [["a": "foo"], ["b": "bar"], ["c": "baz"], ["c": "bazx"]]
let flat = inputArray.reduce([:]) { $0 + $1 }
If you overloaded "+" on Dictionary
func + <K, V>(lhs: [K : V], rhs: [K : V]) -> [K : V] {
var combined = lhs
for (k, v) in rhs {
combined[k] = v
}
return combined
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With