Iterate a loop with index and element in Swift

In this tutorial, we will learn how to iterate over a list in Swift and print the item in the list with its index. Sometimes, we need to work with the item and its index, here this task will prove to be helpful.

We have shown four different methods to do this.

Using an enumerated list to iterate a loop with index and element

This method creates a list and then converts the list into a sequence of pairs, prints the index and element as-

var languages=["C","C++","Swift","Python","R"]
for (index,element) in languages.enumerated()
{
    print("Language \(index): \(element)")
}

Output-

Language 0: C
Language 1: C++
Language 2: Swift
Language 3: Python
Language 4: R

Create a list and refer to its indices

In this method, it is shown how to iterate over a list with indices and print the element with an index. The snippet for this-

var languages=["C","C++","Swift","Python","R"]

for index in languages.indices {
    print("Language:", index, " Value:", languages[index])
}

Output-

Language: 0 Value: C
Language: 1 Value: C++
Language: 2 Value: Swift
Language: 3 Value: Python
Language: 4 Value: R

Iterate over the loop using for-each

This method iterates over the list using for-each and indices. It results in the index with the element as-

var languages=["C","C++","Swift","Python","R"]
languages.indices.forEach {
    print("Language at:", $0, " Value:", languages[$0])
}

Output-

Language at: 0 Value: C
Language at: 1 Value: C++
Language at: 2 Value: Swift
Language at: 3 Value: Python
Language at: 4 Value: R

Iterate the loop using for-each and enumerated in Swift

This method iterates over the list using for-each loop in Swift and enumerated. The snippet for this would be-

var languages=["C","C++","Swift","Python","R"]
languages.enumerated().forEach {
    print("Language at", $0.offset, ":", $0.element)
}

Output-

Language at 0 : C
Language at 1 : C++
Language at 2 : Swift
Language at 3 : Python
Language at 4 : R

This tutorial consists of 4 different methods to iterate over a list and print its index with its element. Thanks for reading, I hope you found this tutorial helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *