find the standard deviation of all values in a map in swift

To find the standard deviation of all values in a map in Swift, you can use the following code:

main.swift
extension Dictionary where Value: FloatingPoint {
    var standardDeviation: Double {
        let values = Array(self.values)
        let mean = values.reduce(0, +) / Double(values.count)
        let deviations = values.map { pow($0 - mean, 2) }
        let variance = deviations.reduce(0, +) / Double(deviations.count)
        return sqrt(variance)
    }
}

// Example usage
var myMap = ["A": 10.0, "B": 20.0, "C": 30.0, "D": 40.0]
let standardDeviation = myMap.standardDeviation
print(standardDeviation) // Output: 11.180339887498949
536 chars
15 lines

The above code extends the Dictionary class to add a new computed property standardDeviation which returns the standard deviation of all values in the dictionary. It first creates an array of all the values in the dictionary, then calculates the mean of those values. It then calculates the deviation of each value from the mean, squares it and adds it to deviations. Finally, it calculates the variance by dividing deviations by the number of values and returns the square root of the variance as the standard deviation.

gistlibby LogSnag