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.swift201 chars7 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