Swift: 3 ways to calculate the average of a numeric array

Updated: April 19, 2023 By: Khue Post a comment

This practical, example-based article walks you through a couple of different approaches to calculating the average (the mean) of all elements in a numeric array (an array that contains only numbers) in Swift. No more wasting time; let’s explore them one by one.

Using the reduce() method

You can use the reduce() method of the array to combine all the elements into a single value. The reduce method takes two parameters: an initial value and a closure that defines how to combine each element with the previous result. You can use reduce() to calculate the sum of the array and then divide it by the count of the array to get the average.

Example:

let numbers = [0.5, 3.4, -1.6, 4.3, -5.0, 7.4]

// calculate the sum of the array
let sum = numbers.reduce(0) { result, number in
    result + number
}

// convert to double and divide by the count of the array
let average = Double(sum) / Double(numbers.count)
print(average)

Output:

1.5

You can rewrite the code above in a one-line style as follows:

let numbers = [0.5, 3.4, -1.6, 4.3, -5.0, 7.4]

// calculate the average of the numbers
let average = numbers.reduce(0.0, +) / Double(numbers.count)

print(average)

Using a for loop

You can iterate over the elements of the array using a for loop, and keep track of the sum and the count of the elements. Then, you can divide the sum by the count to get the average.

Example:

let numbers = [1, 2, 3, 4, 5] 
var sum = 0 
var count = 0

for number in numbers { 
    sum += number 
    count += 1 
}

let average = Double(sum) / Double(count) 
print(average)

Output:

3.0

Using the forEach() method

Example:

let numbers = [1, 2, 3, 4, 5, 6, 7, 9] 

// a variable to store the sum
var sum = 0 

// use forEach() to loop over the array and add each element to the sum
numbers.forEach { sum += $0 } 

// calculate the average
let average = Double(sum) / Double(numbers.count) 
print(average) 

Output:

4.625