This practical, code-centric article will walk you through several different ways to calculate the sum of a numeric array (an array that only contains numerical elements) in Swift.
Using the reduce() method
You can use the reduce() method to apply a function to all the elements in the array and return a single value. The function takes two arguments: an accumulator and an element. The accumulator is the result of the previous iteration, and the element is the current element in the array. The function returns a new accumulator value that is used for the next iteration.
This example demonstrates how to use reduce() to get the sum of an array:
let numbers = [9, -3, 3, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let sum = numbers.reduce(0) { accumulator, element in
accumulator + element
}
print(sum)
Output:
69
You can also use a shorthand syntax for the function by using $0 and $1 as the accumulator and element arguments. This will help you solve the task with just a single line of code (it looks cool but the drawback is the reduction of readability):
let numbers = [9, -3, 3, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// get the job done with only a single line of code
let sum = numbers.reduce (0) { $0 + $1 }
print(sum) // 69
Another single-line solution with reduce():
let numbers = [9, -3, 3, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// get the job done with only a single line of code
let sum = numbers.reduce(0, +)
print(sum) // 69
Using a classic for loop
In programming, a simple for loop is the key that can open a plethora of doors, and it’s still true in the context of this tutorial.
Example:
let numbers = [1, 2, 3, 4, 5]
var sum = 0
for number in numbers {
sum += number
}
print(sum)
Output:
15
Using the forEach() method
Example:
let numbers = [1, 2, 3, 4, 5]
var sum = 0
numbers.forEach { number in
sum += number
}
print(sum)
Output:
15
Using a while loop
Not much difference from the previous approach but I think it is still worth a look.
Example:
let numbers = [1, 2, 3, 4, 5]
var sum = 0
var index = 0
while index < numbers.count {
sum += numbers[index]
index += 1
}
print(sum)
Output:
15
Using a for/in loop
This example finds the sum of double elements in an array:
import Foundation
let numbers: [Double] = [1.5, 2.3, 5.8, 3.2, 10.7, -2.1, 4.5, 6.3, 7.8, 9.1]
var sum: Decimal = 0.0
for number in numbers {
sum += Decimal(number)
}
print(sum)
Output:
49.1