To find the sum of all elements in an array in Swift, one way is to use the reduce
method on the array.
Here is an example code snippet:
main.swift82 chars4 lines
In this code, we have an array of integers [1, 2, 3, 4, 5]
. We then call the reduce
method on the array, passing in two arguments: an initial value of 0
, and a closure which takes in two integers and returns their sum using the +
operator.
The reduce
method iterates over the array, adding each element to the running total, which starts at 0
. The final result is the sum of all the elements in the array. We store this value in the sum
constant and print it out to the console.
gistlibby LogSnag