Creating an array in Swift by applying binary operation to all elements of two other arrays

819 Views Asked by At

Is there a concise way in Swift of creating an array by applying a binary operation on the elements of two other arrays?

For example:

let a = [1, 2, 3]
let b = [4, 5, 6]
let c = (0..<3).map{a[$0]+b[$0]} // c = [5, 7, 9]
2

There are 2 best solutions below

0
On BEST ANSWER

If you use zip to combine the elements, you can refer to + with just +:

let a = [1, 2, 3]
let b = [4, 5, 6]    
let c = zip(a, b).map(+)  // [5, 7, 9]
1
On

Update:

You can use indices like this:

for index in a.indices{
    sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]

(Thanks to Alexander's comment this is better, because we don't have to deal with the element itself and we just deal with the index)

Old answer:

you can enumerate to get the index:

var sum = [Int]()
for (index, _) in a.enumerated(){
    sum.append(a[index] + b[index])
}
print(sum)// [5, 7, 9]