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
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.
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 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.
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 dictionarymerging
returns a new dictionaryvar 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
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With