How to write method to calculate average in Swift-playground
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
You can use the count property of the array:
func average(numbers: Int...) -> Double {
var sum = 0
for number in numbers {
sum += number
}
var ave : Double = Double(sum) / Double(numbers.count)
return ave
}
While others have already pointed out the missing count variable, it is worth noting that you can do the average even more elegantly by using closures as follows:
func averagec(numbers:Int...) -> Double {
return Double(numbers.reduce(0,combine:+))/Double(numbers.count)
}
Edited for Swift 4:-
func averagec(numbers:Int...) -> Double {
return Double(numbers.reduce(0,+))/Double(numbers.count)
}
import Accelerate
let avg = vDSP.mean(array)
This will be at least 50x faster than all other solutions posted so far.