OneBite.Dev - Coding blog in a bite size

Find The Average Of All Elements In An Array In Swift

Code snippet for how to Find The Average Of All Elements In An Array In Swift with sample and detail explanation

Swift—an intuitive and powerful language for iOS, macOS, watchOS, and tvOS app development—is known for its simplicity and versatility. This article focuses on teaching you how to calculate the average of all elements in an array using Swift.

Code Snippet: Calculate The Average Of All Elements In An Array In Swift

Here is a simple Swift code snippet to calculate the average of all elements in an array:

let numbers = [2, 3, 4, 5, 6]
let total = numbers.reduce(0, { $0 + $1 })
let average = Double(total) / Double(numbers.count)
print("Average: \(average)")

Code Explanation: Calculate The Average Of All Elements In An Array In Swift

Let’s break down the code snippet we’ve just seen, step by step.

Step 1 - Initialising the Array:

let numbers = [2, 3, 4, 5, 6]

In this line of the code, we are initializing an array called ‘numbers’ with some arbitrary integer values.

Step 2 - Calculating the Sum of Array Elements:

let total = numbers.reduce(0, { $0 + $1 })

Here, we’re using the reduce() function in Swift. This function combines all items in a collection to create a single new value. The parameters of the function are initially set as zero and the closure $0 + $1 is used to accumulate the sum of all elements in the array.

The $0 and $1 represent cumulative/previous value and the current value in the array respectively during the execution of the closure.

Step 3 - Calculating the Average:

let average = Double(total) / Double(numbers.count)

In this step, we calculate the average by dividing the ‘total’ by the count of numbers in the array.

Note: We have also typecasted ‘total’ & numbers count to Double to enable division between them to produce a floating point number if necessary.

Step 4 - Printing the Result:

print("Average: \(average)")

Finally, we print the average to see the result of our calculation.

And there you have it - a straightforward and simple method of calculating the average of all elements in a Swift array!

swift