Swift: Sum an array of integers using reduce
Video: Swift: Sum an array of integers using reduce by Taught by Celeste AI - AI Coding Coach
Watch full page →Swift: Sum an Array of Integers Using Reduce
In Swift, the reduce function provides a concise way to combine all elements of an array into a single value. Summing an array of integers is a common use case where reduce can simplify your code by iteratively adding each element to an accumulator.
Code
let numbers = [1, 2, 3, 4, 5]
// Use reduce to sum all elements starting from 0
let sum = numbers.reduce(0) { accumulator, current in
accumulator + current
}
print("Sum of array:", sum)
// Output: Sum of array: 15
Key Points
- The
reducemethod takes an initial value and a closure that combines the accumulator with each element. - Starting the accumulator at 0 is essential when summing integers to avoid incorrect results.
- The closure can be written using shorthand syntax:
numbers.reduce(0, +)for brevity. reduceis a powerful tool for aggregating array values beyond just summing numbers.