The Nomad The Nomad - 29 days ago 11
iOS Question

Swift: how to combine two Dictionary instances?

How do I append one

[Dictionary]
to another
[Dictionary]
using
Swift
?

I am using the
AlamoFire
library to send a
JSON
to a
REST server
.

Dictionary 1

let dict1: [String: AnyObject] = [
kFacebook: [
kToken: token
]
]


Dictionary 2

let dict2: [String: AnyObject] = [
kRequest: [
kTargetUserId: userId
]
]


How do I combine the two dictionaries to achieve like below?

let parameters: [String: AnyObject] = [
kFacebook: [
kToken: token
],
kRequest: [
kTargetUserId: userId
]
]


I have tried
dict1 += dict2
but got a compile error.

Thanks in advance!

Answer
var d1 = ["a": "b"]
var d2 = ["c": "e"]

extension Dictionary {
    mutating func merge<K, V>(dict: [K: V]){
        for (k, v) in dict {
            self.updateValue(v as Value, forKey: k as Key)
        }
    }
}

d1.merge(d2)

Refer to the awesome Dollar & Cent project https://github.com/ankurp/Cent/blob/master/Sources/Dictionary.swift