harsh_v
harsh_v

Reputation: 3269

Swift reduce/flatten Dictionary<String,Dictionary> to Dictionary

Convert this

[ 
   "Cat" : ["A" : 1, "B": 2], 
   "Mat" : ["C" : 3, "D": 4]
]

Into

[
    "A" : 1, 
    "B" : 2,
    "C" : 3,
    "D" : 4
]

Without using a loop. In other terms using functions like reduce, flatmap.

The source can be of type Dictionary<String,Dictionary<String,String>>


So far I've managed to reduce the Dictionary to an array of Dictionary

let flatten = source.flatMap({ (k,v) -> [String: String]? in
                            return v
                        })

// flatten = [["A" : 1, "B": 2], ["C" : 3, "D": 4]]]

Upvotes: 2

Views: 1832

Answers (1)

Sulthan
Sulthan

Reputation: 130102

One option:

let dictionary = [
    "Cat" : ["A" : 1, "B": 2],
    "Mat" : ["C" : 3, "D": 4]
]

let merged = dictionary
   // take values, we don't care about keys
   .values
   // merge all dictionaries
   .reduce(into: [:]) { (result, next) in
      result.merge(next) { (_, rhs) in rhs }
   }
print(merged) // ["B": 2, "A": 1, "C": 3, "D": 4]

Upvotes: 3

Related Questions