Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add elements of two arrays in Swift without appending together

Tags:

arrays

swift

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

like image 255
George Puttock Avatar asked Jan 03 '17 23:01

George Puttock


People also ask

How do I add two arrays in Swift?

To append or concatenate two arrays in Swift, use plus + operator with the two arrays as operands.

How do I add an element from two arrays?

You cannot use the plus operator to add two arrays in Java e.g. if you have two int arrays a1 and a2, doing a3 = a1 + a2 will give a compile-time error. The only way to add two arrays in Java is to iterate over them and add individual elements and store them into a new array.


1 Answers

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(+)
like image 126
twiz_ Avatar answered Nov 15 '22 08:11

twiz_