{

Multiple ways to iterate a loop with index and element in array in swift


This tutorials shows multiple ways to iterate an array with index.

Swift provides collection type such as Arrays, sets, and dictionaries.

Let’s see an example for multiple ways to iterate an loop with index and an element in Swift array.

How to iterate a loop with index an element in Swift Array?

We use for loop to iterate an element in swift for-in loop iterates the loop for number of elements in an array.

let numbers =  [10,20,30,40,50,60]
for item in numbers {
    print(item)
}

Output:

10
20
30
40
50
60

There are multiple ways to iterate an loop with index and value.

First way, use enumerated() method

if you want to get an index and value, use enumerated() method provides.

This works in Swift 3 & 4 versions only.

enumerated method returns an tuple that contains index and element for each element iteration.

Index always starts at zero based, first element is 0 and last element index is length of an array - 1.

let numbers =  [10,20,30,40,50,60]
for (index, item) in numbers.enumerated() {
    print("\(index) - \(item)")
}

Output:

0 -  10
1 -  20
2 -  30
3 -  40
4 -  50
5 -  60

Second way using foreach method in swift 5 version for enumerated method

let numbers =[10, 20, 30, 40, 50, 60]
  numbers.enumerated ().forEach { (index, item) in
print ("\(index) -  \(item)")
}
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.