Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Combine Dictionaries in an Array

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?

like image 261
garetmckinley Avatar asked Jan 20 '15 04:01

garetmckinley


1 Answers

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
}
like image 130
Jawwad Avatar answered Sep 28 '22 07:09

Jawwad