Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 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

like image 627
The Nomad Avatar asked Nov 04 '14 05:11

The Nomad


People also ask

Can I use two dictionaries to merge?

You can merge two dictionaries using the | operator. It is a very convenient method to merge dictionaries; however, it is only used in the python 3.9 version or more.

How do I merge two dictionaries in a single expression?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

How do you combine values in a dictionary?

How to Merge Dictionaries in Python Using the dict. update() Method. If you explore the dict class, there are various methods inside it. One such method is the update() method which you can use to merge one dictionary into another.


3 Answers

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
like image 163
blackjacx Avatar answered Oct 16 '22 18:10

blackjacx


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

like image 85
Shuo Avatar answered Oct 16 '22 17:10

Shuo


For Swift >= 2.2:
let parameters = dict1.reduce(dict2) { r, e in var r = r; r[e.0] = e.1; return r }

For Swift < 2.2:
let parameters = dict1.reduce(dict2) { (var r, e) in r[e.0] = e.1; return r }

Swift 4 has a new function: let parameters = dict1.reduce(into: dict2) { (r, e) in r[e.0] = e.1 }

It's really important to dig around the standard library: map, reduce, dropFirst, forEach etc. are staples of terse code. The functional bits are fun!

like image 19
emp Avatar answered Oct 16 '22 18:10

emp