Combining two dictionaries in Swift

Swift gives us many new features, such as (finally!), Concatenating strings, and even arrays. But there is no support for dictionaries. The only way to connect dictionaries is to overload + operation for them?

let string = "Hello" + "World" // "HelloWorld"
let array = ["Hello"] + ["World"] // ["Hello", "World"]
let dict = ["1" : "Hello"] + ["2" : "World"] // error =(
+4
source share
3 answers

Use it as follows:

  • Put it anywhere, for example. Dictionary + .swift Extension :

    func +<Key, Value> (lhs: [Key: Value], rhs: [Key: Value]) -> [Key: Value] {
        var result = lhs
        rhs.forEach{ result[$0] = $1 }
        return result
    }
    
  • Now your code just works

    let string = "Hello" + "World" // "HelloWorld"
    let array = ["Hello"] + ["World"] // ["Hello", "World"]
    let dict = ["1" : "Hello"] + ["2" : "World"] // okay =)
    

Edit:

As @Raphael suggested, the sign +means that the calculation is commutative. Keep in mind that this is not the case. for example, the result of [2: 3] + [2: 4]vs is [2: 4] + [2: 3]not the same.

+15
source

, . , .

var dict = ["1" : "Hello"]
let dict2 = ["2" : "World"]

for key in dict2.keys {
    dict[key] = dict2[key]
}
+10

You can also use Swift functions to perform a merge:

public func +<K, V>(left: [K:V], right: [K:V]) -> [K:V] {
    return left.merging(right) { $1 }
}

$ 1 will take the shared keys from the dictionary on the right, you can use $ 0 if you want to give priority to the left diction.

0
source

Source: https://habr.com/ru/post/1611787/


All Articles