Building on this question, I am trying to calculate the variance of an array of Int.
My extension looks like this so far:
extension Array where Element: Integer {
/// Returns the sum of all elements in the array
var total: Element {
return reduce(0, combine: +)
}
/// Returns the average of all elements in the array
var average: Double {
return isEmpty ? 0 : Double(total.hashValue) / Double(count)
}
/// Returns an array of the squared deviations from the mean
var squaredDeviations: [Double] {
let mean = average
return isEmpty ? 0 : map( { number in
let difference = Double(number) - mean
return pow(distance, 2)
})
}
}
Total and average work fine, but for squaredDifferences it appears that you must return the same type as the array when using map
. Is there a way to get around this?
Update I was receiving the compiler error:
Result values in '? :" expression have mismatching types 'Int' and '[ _ ]'
The problem was that I was returning 0 which is not an array of Doubles. Also I was not using number.hashValue, and therefor couldn't initialize the double.