How to write method to calculate average in Swift-playground

user1898829 picture user1898829 · Jun 9, 2014 · Viewed 16.9k times · Source

In swift I'm trying to write a method to calculate the average. Using the method below if i type average(5,10,15) I get infinity displayed in the swift-playforund

func average(numbers: Int...) -> Double {
    var sum = 0
    var count = 0
    for number in numbers {
        sum += number
    }
    var  ave : Double = Double(sum) / Double(count)
    return ave
}

Answer

GarlicFries picture GarlicFries · Jan 5, 2015

It's so much easier with just a straightforward call to reduce:

let array = [1.0,2.0,3.0]
var average = array.reduce(0.0) {
    return $0 + $1/Double(array.count)
}
// average = 2.0