How to iterate a loop with index and element in Swift?


In this article, you will learn how to iterate a collection using a loop with an index and element in the Swift language. In this article, you will learn how to use the enumerated() method.

In Swift, you can use the enumerated() method to iterate over the elements of a collection and access both the index and the element in each iteration of the loop.

enumerated()

enumerated() is a method in Swift that allows you to iterate over the elements of a collection, such as an array or a dictionary. It returns a series of tuple elements, each of which contains an index of the element and the element itself.

Here is an example of how to use enumerated() to iterate over an array −

Algorithm

  • Step 1 - Create an input array to iterate

  • Step 2 - Iterate over the input array with the enumerated() method

  • Step 3 - Hold the returned tuple of index and element

Example

import Foundation
// creating an input array
let languages: [String] = ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
// iterating over the input array
for (index, element) in languages.enumerated() {
    print("Element \(element) at index \(index)")
}

Output

This will print the following output

Element PHP at index 0
Element Java at index 1
Element Swift at index 2
Element Python at index 3
Element JavaScript at index 4
Element GoLang at index 5

You can iterate a loop with an index and element with manual value like below

import Foundation
// creating an input array
let languages: [String] = ["PHP", "Java", "Swift", "Python", "JavaScript", "GoLang"]
// iterating over the input array
var index = 0
for element in languages {
    print("Element \(element) at index \(index)")
    index += 1
}

Output

This will print the following output

Element PHP at index 0
Element Java at index 1
Element Swift at index 2
Element Python at index 3
Element JavaScript at index 4
Element GoLang at index 5

Conclusion

You can iterate in a loop to get the index and element using different methods. Nevertheless, enumerated() is always recommended for iterating.

Updated on: 07-Sep-2023

342 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements