find the average of all values in a map in swift

To find the average of all the values in a Swift map, you can use the reduce function to iterate through all the values in the map and calculate the sum. Then divide the sum by the total number of values present in the map.

Here's an example code snippet that demonstrates how to find the average of all values in a Swift map:

main.swift
let myMap = ["A": 10, "B": 20, "C": 30]

let sum = myMap.values.reduce(0, +)
let average = Double(sum) / Double(myMap.count)

print("Average value is:", average)
162 chars
7 lines

In this example, we first initialize a dictionary myMap with some key-value pairs. Then, we use the reduce method to add up all the values in the map. Finally, we divide the sum by the total count of values in the map to find the average value.

The output of the above code will be:

main.swift
Average value is: 20.0
23 chars
2 lines

related categories

gistlibby LogSnag