find the variance of all values in a map in swift

To find the variance of all values in a map in Swift, we can follow the steps below:

  1. Calculate the mean of all values in the map.
  2. For each value in the map, subtract the mean and square the result.
  3. Calculate the average of all the squared differences.

Here's the implementation:

main.swift
extension Dictionary where Value: Numeric {
    var variance: Value? {
        guard !isEmpty else { return nil }

        let mean = reduce(into: 0) { (result, element) in
            result += element.value
        } / Value(count)

        let squaredDifferencesSum = reduce(into: 0) { (result, element) in
            let difference = element.value - mean
            result += difference * difference
        }

        return squaredDifferencesSum / Value(count - 1)
    }
}
481 chars
17 lines

With this implementation, we can get the variance of a dictionary with numeric values by simply calling the variance property:

main.swift
let map = ["a": 1, "b": 2, "c": 3]
print(map.variance) // Optional(1.0)
72 chars
3 lines

Note that the variance property returns an optional value, since the variance is undefined for an empty map. If the map has only one value, the function will return nil, since the variance is undefined for a single value. Also, note that we use a Numeric constraint on the map's value type, which means that the value type must conform to the Numeric protocol (e.g., Int, Double, Float, etc.).

gistlibby LogSnag