How to combine two Dictionary instances in Swift? How to combine two Dictionary instances in Swift? ios ios

How to combine two Dictionary instances in Swift?


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


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


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!