How to combine two Dictionary instances in Swift?

The Nomad picture The Nomad · Nov 4, 2014 · Viewed 53.6k times · Source

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

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 got a compile error:

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

Answer

blackjacx picture blackjacx · Apr 25, 2017

I love this approach:

dicFrom.forEach { (key, value) in dicTo[key] = value }

Swift 4 and 5

With Swift 4 Apple introduces a better approach to merge two dictionaries:

let dictionary = ["a": 1, "b": 2]
let newKeyValues = ["a": 3, "b": 4]

let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current }
// ["b": 2, "a": 1]

let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new }
// ["b": 4, "a": 3]

You have 2 options here (as with most functions operating on containers):

  • merge mutates an existing dictionary
  • merging returns a new dictionary