Why is it so hard to find examples of Swift dictionary reduce operations? Examples for arrays abound :

let countme = [1, 2, 3, 4, 5]
let sumall = countme.reduce(0){$0+$1}
// sumall is now 15

See this if you’re looking for a detailed HowTo.

But dictionary is the more advanced problem. How do I reduce when I have keys and values?

The key here is to note that a dictionary yields the contents of its sequence in tuples containing pairs of values. We still have our familiar $0, $1 arguments from reduce as above, where $0 is the partial sum and $1 is the individual element value. But now $0 and $1 are both tuples, and you get to their contents through $0.0, $0.1, $1.0, and $1.1.

let namesNumbers = ["Mike":21, "Bruce":25, "Alice":27]
let (bigname,bignumber) = namesNumbers.reduce(("",0)) 
  {return ($0.0 + $1.0, $0.1 + $1.1)}

This example concatenates the strings and adds the integers, and the two separate data types just happen to use the same symbol for the two operations.

Leave a Reply