How to get index and value from for loop with Swift

How to get index and value from for loop with Swift

Sometimes I find that I need to get both the index and the value when I am looping through an array. In this tutorial I will show you how to get both.

I have the following array of programming languages:

let languages = ["Swift", "Kotlin", "JavaScript", "Python", "Dart"]

Normally when we loop through this we would use a for in loop, and in this case we will still use a for in. The difference, when we want to get both index and value is to make use of the enumerated method. Luckily for us, the enumerated method is part of Array.

So, this is the how the loop will look:

for (index, language) in languages.enumerated() {
    print("\(index):\(language)")
}

Instead of the usual for language in languages we use the enumerated method. enumerated will return a sequence of pairs where each pair will contain the index and the value for the corresponding item in the array.

You can find the full source code here.