find the average of all keys in a map in swift

To find the average of all keys in a map (i.e. dictionary) in Swift, we can use the reduce method to add up all the keys and then divide by the count of keys. Here's a code snippet to illustrate this:

main.swift
let map = ["a": 1, "b": 2, "c": 3]

let sumOfKeys = map.keys.reduce(0.0) { $0 + Double($1)! }
let averageOfKeys = sumOfKeys / Double(map.count)

print(averageOfKeys) // 1.0 + 2.0 + 3.0 = 6.0 / 3 = 2.0
201 chars
7 lines

In this code, we first define a map (i.e. Dictionary) with string keys and integer values. Then, we use the reduce method on the keys property of the map to add up all the keys as doubles. Note that we force-unwrap the key values as doubles using Double($1)! inside the closure. Finally, we divide the sum of keys by the count of keys to get the average. In this case, the average is 2.0.

gistlibby LogSnag