3

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]
Danra
  • 9,546
  • 5
  • 59
  • 117
  • 1
    "Almost" duplicate (same question for multiplication instead of addition) http://stackoverflow.com/questions/39724115/swift-how-to-multiply-array-by-array-math-vector-by-vector. – Martin R Dec 18 '16 at 15:05

2 Answers2

15

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]
vacawama
  • 150,663
  • 30
  • 266
  • 294
0

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]
mfaani
  • 33,269
  • 19
  • 164
  • 293
  • 1
    There's no reason to be using `enumerated` if you're only interested in the index or the element, but not both. Otherwise, just use `a.indices` – Alexander Sep 20 '17 at 00:35