How do I append one Dictionary
to another Dictionary
using Swift
?
I am using the AlamoFire
library to send a
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 dictionaryYou are using let keyword to declare the dictionary so you can't make the changes to your dictionary as it is used to declare constant.
Change it to var keyword then it will work for you.
var dict1: [String: AnyObject] = [
kFacebook: [
kToken: token
]
]
var dict2: [String: AnyObject] = [
kRequest: [
kTargetUserId: userId
]
]
dict1 += dict2
SequenceType.forEach
(implemented by Dictionary
) provides an elegant solution to add a dictionary's elements to another dictionary.
dic1.forEach { dic2[$0] = $1 }
For example
func testMergeDictionaries() {
let dic1 = [1:"foo"]
var dic2 = [2:"bar"]
dic1.forEach { dic2[$0] = $1 }
XCTAssertEqual(dic2[1], "foo")
}
We can merge dictionaries in a better way using merge keyword
var dictionary = ["a": 1, "b": 2]
/// Keeping existing value for key "a":
dictionary.merge(["a": 3, "c": 4]) { (current, _) in current }
// ["b": 2, "a": 1, "c": 4]