jsonswiftdictionary

How can I combine two Dictionary instances in Swift?


How do I append one Dictionary to another Dictionary using Swift?

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

Dictionary 1

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

Dictionary 2

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

How do I combine the two dictionaries to make a new dictionary as shown below?

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

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

Binary operator '+=' cannot be applied to two '[String : AnyObject]' operands


Solution

  • var d1 = ["a": "b"]
    var d2 = ["c": "e"]
    
    extension Dictionary {
        mutating func merge(dict: [Key: Value]){
            for (k, v) in dict {
                updateValue(v, forKey: k)
            }
        }
    }
    
    d1.merge(d2)
    

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