sum an array of numbers in swift

You can use the reduce method in Swift to sum an array of numbers. Here's an example:

main.swift
let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(0, { $0 + $1 })
print(sum) // Output: 15
96 chars
4 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.

related categories

gistlibby LogSnag