find the sum of all values in a map in swift

To find the sum of all values in a Map (Dictionary) in Swift, you can use the reduce method provided by the Dictionary type. The reduce method iterates through every element in the dictionary, and applies a provided closure to combine the values.

Here's an example code snippet that demonstrates how to use the reduce method to calculate the sum of all values in a Map:

main.swift
let dictionary = ["A": 1, "B": 2, "C": 3, "D": 4, "E": 5]

let sum = dictionary.reduce(0) { $0 + $1.value }

print("The sum of all values in the dictionary is: \(sum)")
169 chars
6 lines

In this example, we start with an initial value of 0 for the sum, and then use the reduce method to add up all the values in the dictionary by accessing the .value property of each key-value pair. The closure passed to reduce returns the accumulated sum plus the value of the current element.

The output of this code snippet will be:

main.swift
The sum of all values in the dictionary is: 15
47 chars
2 lines

Therefore, the sum of all values in the dictionary is 15.

related categories

gistlibby LogSnag