find the average of all elements in an array in swift

To find the average of all elements in an array in Swift, you can use the reduce function to sum up all the elements in the array and then divide by the number of elements in the array. Here's the code to do that:

main.swift
let numbers = [1, 2, 3, 4, 5]

let sum = numbers.reduce(0, +) // sum up all the elements in the array

let average = Float(sum) / Float(numbers.count) // divide by the number of elements in the array

print("The average is: \(average)")
237 chars
8 lines

The output of this code will be:

main.swift
The average is: 3.0
20 chars
2 lines

gistlibby LogSnag