Question: Add elements of two arrays in Swift without appending together

Question

Add elements of two arrays in Swift without appending together

Answers 1
Added at 2017-01-04 00:01
Tags
Question

Is there a neat way to add two arrays in Swift:

IE I would like

let arrayA: [Float] = [1,2,3,4]
let arrayB: [Float] = [10,20,30,40]

let arrayResult:[Float] = arrayA.map({($0) + ***stuck here***})

I would like the arrayResult to be [11,22,33,44] and not [1,2,3,4,10,20,30,40] that you would get should you were to do:

let arrayResult = arrayA + arrayB

I know it is possible with:

for i in arrayA{
  arrayResult[i] = arrayA[i] + arrayB[i]
}

But there must be a neater way than this using closures (that I can't fully grasp currently)

Thanks

Answers to

Add elements of two arrays in Swift without appending together

nr: #1 dodano: 2017-01-04 00:01

Indeed there is an easier way. Zip then map.

let arrayA: [Float] = [1,2,3,4]
let arrayB: [Float] = [10,20,30,40]

let arrayResult:[Float] = zip(arrayA,arrayB).map() {$0 + $1}

edit: Even prettier from the comment below:

let arrayResult:[Float] = zip(arrayA,arrayB).map(+)
Source Show
◀ Wstecz