Looping over dictionary keys and values

Jul 24, 2014 00:00 · 196 words · 1 minute read swift

In plenty of other languages looping over both the keys and the values in a dictionary is non-trivial; it requires some special fooling around with references rather clunkily. One of my favourite things about Swift is that it allows you to evaluate both the keys and the values of a dictionary at one time, with finesse.

Consider

let worldCupGroupsABGoals = [
    "Brazil": [3, 0, 4],
    "Mexico": [1, 0, 3],
    "Croatia": [1, 4, 1],
    "Cameroon": [0, 0, 1],
    "Netherlands": [5, 3, 2],
    "Chile": [3, 2, 0],
    "Spain": [1, 0, 3],
    "Australia": [1, 2, 0],
]

var mostGoals = 0
var countryMostGoalsInSingleMatch: String?

for (country, goals) in worldCupGroupsABGoals {
    for goalCount in goals {
        if goalCount > mostGoals {
            mostGoals = goalCount
            countryMostGoalsInSingleMatch = country
        }
    }
}

mostGoals
countryMostGoalsInSingleMatch

Go ahead and run this in a Playground; you will find that we get not only the most goals scored in a single match, but which country by key. Smooth.

The astute observer will notice that if we had two matches with identical goal counts then our final values will be whichever key-value pair was evaluated last. I leave solving this as an exercise to the reader. :-)