How to combine 2 maps into a third map in Swift

2 Answers

0 votes
import Foundation

let map1 = ["a": 1, "b": 2]
let map2 = ["b": 999, "c": 4, "d": 5]

let combined = map1.merging(map2) { (_, new) in new }

print(combined)




/*
run:

["c": 4, "b": 999, "a": 1, "d": 5]

*/

 



answered Aug 26, 2025 by avibootz
0 votes
import Foundation

let map1 = ["a": 1, "b": 2]
let map2 = ["b": 999, "c": 4, "d": 5]

let combined = map1.merging(map2) { old, new in old + new }

print(combined)




/*
run:

["d": 5, "c": 4, "a": 1, "b": 1001]

*/

 



answered Aug 26, 2025 by avibootz

Related questions

1 answer 88 views
2 answers 99 views
3 answers 110 views
2 answers 127 views
1 answer 89 views
2 answers 106 views
3 answers 116 views
...