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

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.

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