find the average of a list of numbers in swift

To find the average of a list of numbers in Swift, you can do the following:

main.swift
let numbers = [2, 4, 6, 8, 10]
let sum = numbers.reduce(0, +)
let average = sum / numbers.count
print(average) // Output: 6
124 chars
5 lines

The reduce method is used to calculate the sum of all the numbers in the list. The reduce method takes two arguments: the starting value, which is 0 in this case, and a closure that specifies how to combine the elements of the array to produce a single result. The sum variable will contain the result of the sum.

Once you have the sum, you can divide it by the number of elements in the list to get the average. The count property is used to get the number of elements in the list. The average variable will contain the average of the numbers.

Finally, the print function is used to output the result to the console.

gistlibby LogSnag