find the sum of all keys in a map in swift

To find the sum of all keys in a dictionary (map) in Swift, we can iterate over the keys of the dictionary and add their values to a running total. Here's an example:

main.swift
let myDictionary = ["foo": 1, "bar": 2, "baz": 3]

var sum = 0
for key in myDictionary.keys {
    sum += key
}

print(sum) // Output: 6
136 chars
9 lines

In this example, we have a dictionary called myDictionary with keys "foo", "bar", and "baz", each with an associated value of 1, 2, and 3, respectively. We then initialize a variable sum to 0, and iterate over the keys of the dictionary using the keys property.

Inside the loop, we add the current key to the running total sum. Finally, we print the value of sum, which should be 6 (the sum of 1 + 2 + 3).

related categories

gistlibby LogSnag