Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two dictionaries in Swift

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 =(
like image 809
katleta3000 Avatar asked Oct 15 '15 12:10

katleta3000


2 Answers

Use it like this:

  1. 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
     }
    
  2. Now your code just work

     let string = "Hello" + "World" // "HelloWorld"
     let array = ["Hello"] + ["World"] // ["Hello", "World"]
     let dict = ["1" : "Hello"] + ["2" : "World"] // okay =)
    
like image 200
Yuchen Avatar answered Sep 17 '22 13:09

Yuchen


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]
}
like image 21
Adam Avatar answered Sep 21 '22 13:09

Adam