Swift: Flatten an array of dictionaries to one dictionary

Lneuner picture Lneuner · Feb 24, 2016 · Viewed 10.6k times · Source

In Swift, I am trying to flatten an array of dictionaries into one dictionary i.e

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


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

I have tried using flatmap, but the type of the returned result is [(String, AnyObject)] and not [String, Object] ie

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

So I have 2 questions:

  • Why is type [(String, AnyObject)] returned? And what do the brackets mean?

  • How do I achieve the desired result?

Edit: I would prefer to use a functional approach with Swift's map/flatmap/reduce etc. instead of a for-loop

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Feb 24, 2016

what do the brackets mean?

This, along with a comma instead of a colon, should provide the first clue: brackets mean that you get an array of tuples. Since you are looking for a dictionary, not an array, this tells you that you need to convert the sequence of tuples (key-value pairs) to a single dictionary.

How do I achieve the desired result?

One way to do it would be using reduce, like this:

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