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
To append or concatenate two arrays in Swift, use plus + operator with the two arrays as operands.
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.
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(+)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With