Overloading for Dictionaries

suggest change

Swift 4 and later can merge dictionaries with merge(_:uniquingKeysWith:) and merging(_:uniquingKeysWith:). On earlier versions, overload + and += with generics. Dictionary keys must be Hashable. Display order is not guaranteed.

// Combines two dictionaries together. If both dictionaries contain
// the same key, the value of the right hand side dictionary is used.
func +<K: Hashable, V>(lhs: [K : V], rhs: [K : V]) -> [K : V] {
    var combined = lhs
    for (key, value) in rhs {
        combined[key] = value
    }
    return combined
}

// The mutable variant of the + overload, allowing a dictionary
// to be appended to 'in-place'.
func +=<K: Hashable, V>(inout lhs: [K : V], rhs: [K : V]) {
    for (key, value) in rhs {
        lhs[key] = value
    }
}

As of Swift 3, inout should be placed before the argument type.

func +=<K: Hashable, V>(lhs: inout [K : V], rhs: [K : V]) { ... }

Example usage:

let firstDict = ["hello" : "world"]
let secondDict = ["world" : "hello"]
var thirdDict = firstDict + secondDict // ["hello": "world", "world": "hello"]

thirdDict += ["hello":"bar", "baz":"qux"] // ["hello": "bar", "baz": "qux", "world": "hello"]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents