S
S
Slava Kolos2016-04-28 23:04:01
Swift
Slava Kolos, 2016-04-28 23:04:01

How to merge two arrays in Swift?

Can't merge two arrays into one

var airports  = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports2 = ["YYZ2": "Toronto Pearson2", "DUB2": "Dublin2"]
var airports3 = airports + airports2

swears like this << binary operator '+' cannot be applied to two '[String : String]' operands>>
what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
DevMan, 2016-04-29
@kolosslava

they are not arrays, but dictionaries ( dictionary ).

extension Dictionary {
  mutating func merge(other:Dictionary) {
    for (key,value) in other {
      self.updateValue(value, forKey:key)
    }
  }
}

let airports  = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
let airports2 = ["YYZ2": "Toronto Pearson2", "DUB2": "Dublin2"]
var airports3 = [String : String]()
airports3.merge(airports)
airports3.merge(airports2)

print(airports3)
// ["YYZ": "Toronto Pearson", "YYZ2": "Toronto Pearson2", "DUB": "Dublin", "DUB2": "Dublin2"]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question