Apr 17 2020

The for in loop: Arrays


In your apps, you often want to loop over an array. In Swift you can do that very easily using a for in loop. The for in loop loops over an array and each time it “hits” an item, the code of the for in loop gets executed. You have acces to the value of the current item of the array with the variable that you specify before the in.

How to use the for in loop.

You can use the for in loop as follows:

Let’s say, you have an array and you want to print out a message together with the value of all the items in the array, all printed separately to the console.

let array = ["hello", "world", "how", "are", "you", "doing"]

for word in array {
    print("the word is: \(word)")

Let’s explain that code. You first write the keyword for which is just saying this is the start of the for in loop. Then, you specify a word or a letter. This could be any word or letter it doesn’t mind which one, it just have to make sense to at least you. Then, you have the in keyword, which will become clear soon. After that keyword, we have the array we want to loop over which can be any array.

So, the in keyword. What this does, is it makes the code more readable. If you read this like English, you see why I say that:

for word in array If you add just one “the”, it reads like this: “For word in the array”

As you see, that is actually plain English. Swift has a lot more of these small things to make it really readable so that actually anyone can read it without knowing what it does. That is one of the powers of Swift and why I like it that much.

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