roher roher - 3 months ago 7
Swift Question

How to combine two complex Dictionaries

I'm curious how to combine two dictionaries which one of them contains key with array or another dictionary as value.

for simple combining e.g.

var dict1 = ["bbb":"dict1",
"her": "dict1"]

let dict2 = ["aaa":"dict2",
"her": "doct2",
"bob": "doct2"]

dict1 += dict2 // result is as I expected


func += <K, V> (inout left: [K:V], right: [K:V]) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}


But problem rise when I want to combine more complex dictionary e.g.

var dict1 = ["bbb":"dict1",
"her": "dict1"]


let complexDict2 = ["aaa":"dict2",
"her": "dict2",
"arr": ["one", "two"]]


dict1 += complexDict2 // in here method which override '+=' operator for dictionaries does not work anymore...


My question is whether you guys have a proved way to combine more complex dictionaries?

Upadate

My expected result from combining dict1 and complexDict2 is :

let resultDict = ["aaa":"dict1",
"aaa":"dict2",
"her": "dict2",
"arr": ["one", "two"]]

Answer

The issue here lies in the types of dict1 and complexDict2.

dict1 is inferred to have type [String : String], whereas complexDict2 is inferred to have type [String : Any].

Your code works just fine, if you explicitly specify a type annotation on dict1:

var dict1: [String : Any] = [
    "aaa":"dict1",
    "her": "dict1"
]
Comments