0

I found the code snippet from this thread: https://stackoverflow.com/a/24052094/2754218 and tested it in a Playground.

func +=<K, V> (inout left: [K: V], right: [K: V]){ 
  for (k, v) in right { 
    left[k] = v
  }
}

var test = ["1": "a"] += ["2": "b"]

The code causes: Binary operator '+=' cannot be applied to two [String : String] operands.

Any suggestion?

SOLUTION:

Thanks to Eric's I create a function with the operator "+":

func +<K, V> (left: [K: V], right: [K: V]) -> [K: V] {
  var newDic = left

  for (k, v) in right {
    newDic[k] = v
  }

  return newDic
}

var toto = ["1": "a"] + ["2": "b"]
Community
  • 1
  • 1
Jean Lebrument
  • 5,079
  • 8
  • 33
  • 67

1 Answers1

1

This function does not return anything, it passes the first value as an inout, meaning it will mutate the left hand object itself:

var test = ["1": "a"]

test += ["2": "b"]

print(test)  // ["2": "b", "1": "a"]
Eric Aya
  • 69,473
  • 35
  • 181
  • 253