Swift gives us plenty new abilities like (at last!) concatenating strings and even arrays. But no support for dictionaries. Is the only way to concatenate 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 =(
Use it like this:
Put this anywhere, e.g. Dictionary+Extension.swift:
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 work
let string = "Hello" + "World" // "HelloWorld"
let array = ["Hello"] + ["World"] // ["Hello", "World"]
let dict = ["1" : "Hello"] + ["2" : "World"] // okay =)
That is not possible because there can be matching keys in the second dictionary. But you can do it manually and the values in the dictionary will be replaced in that case.
var dict = ["1" : "Hello"]
let dict2 = ["2" : "World"]
for key in dict2.keys {
dict[key] = dict2[key]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With