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
}
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