You can use the reduce
method in Swift to sum an array of numbers. Here's an example:
main.swift96 chars4 lines
In this code, reduce
takes two arguments: an initial value for the sum (0 in this case), and a closure that defines how to combine each element of the array with the running sum. The closure takes two arguments: the running sum (initialized to the initial value), and the current element of the array. It returns the sum of the running sum and current element.
The $0
and $1
in the closure are shorthand references to the first and second argument of the closure, respectively.
gistlibby LogSnag