Apr 19 2020

Looping over Dictionaries


In swift, like Array's you also have dictionaries which you can also loop over with the for in loop. In this article I want to show you how to do that.

One of the crucial differences between arrays and dictionaries, is that array's are sorted, but dictionaries are not. If you try the example below a few times yourself you will see the outcome of what it means not being sorted. But of course, this is not a article about Dictionaries. So, let's get started.

How to

This is how you would loop over an dictionary:

let numberOfAnimalLegs = ["spider": 8, "ant": 6, "dog": 4, "gorilla": 2]

for (animalname, numberOfLegs) in numberOfAnimalLegs {
    print("a \(animalname) has \(numberOfLegs) legs")

That will print out this:

a dog has 4 legs
a ant has 6 legs
a gorilla has 2 legs
a spider has 8 legs

At the first look, this code seems like a regular for in loop. But, if you look closely, after the for keyword there are 2 parameters specified in parentheses: animalName and numberOfLegs. You see, I first specified the animal name, and then the number of legs. This is not because swift magically sees that one needs to be a string, and the other one an integer and assigns the string to the string etc(as much I would love if swift had that built-in). But, this is because when looping over a dictionary, you specify the parameter names in the order key-value. In our case this is first a String, the animal name, then an Integer, the number of legs. After that, it is just the regular for in loop, and you have acces to both of the parameters so you can apply your own logic.

Don’t forget that you can email me at for any questions, feedback or if you just wanted to say hi.