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.swift169 chars6 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.swift47 chars2 lines
Therefore, the sum of all values in the dictionary is 15.
gistlibby LogSnag