How to For Loop with Index in Swift

swift for loop index

To assign an index to array items in for loop in Swift, call Array.enumerated() method.

let names = ["Alice", "Bob", "Charlie"]

let names_with_index = names.enumerated()

for (index, name) in names_with_index {
    print(index, name)
}

Output:

0 Alice
1 Bob
2 Charlie

Why Use Array.enumerated() in Swift

Enumerating an array in Swift is useful when looping through arrays.

Sometimes you need to know the index of each item when looping.

One option is to keep track of a separate index.

For example:

let names = ["Alice", "Bob", "Charlie"]

var i = 0
for name in names {
    print(name, i)
    i += 1
}

But this increases the code complexity—you have to keep track of a separate index and update it on each iteration.

This is where enumerating an array comes in handy.

Instead, you can call Array.enumerated() on the array. This couples each array element with an index. You can use this index when looping through the array elements.

For example, let’s print each person in a queue with their position in the queue:

let names = ["Alice", "Bob", "Charlie"]

let names_with_index = names.enumerated()

for (index, name) in names_with_index {
    print("\(name) is at position \(index)")
}

Output:

Alice is at position 0
Bob is at position 1
Charlie is at position 2

By the way, usually, you don’t want to create a separate variable for the enumerated array. Instead, you can place it directly into a for loop:

let names = ["Alice", "Bob", "Charlie"]

for (index, name) in names.enumerated() {
    print("\(name) is at position \(index)")
}

What Is an EnumeratedSequence Object in Swift

Calling array.enumerated() on an array returns a EnumeratedSequence object. This is a sequence of tuples. Each tuple is a pair of (offset, element), where the offset is the index and the element is the corresponding item in the array.

For example:

let names = ["Alice", "Bob", "Charlie"]

let names_with_index = names.enumerated()

print(names_with_index)

Output:

EnumeratedSequence<Array<String>>(_base: ["Alice", "Bob", "Charlie"])

You can loop through the EnumeratedSequence just like you would loop through an array of tuples. You can apply regular array methods to it too, such as map or filter.

Conclusion

Today you learned what the Array.enumerated() function does. You can now reduce code complexity by adding an index into array elements in for loop.

The Array.enumerated() function assigns an index for each element of an iterable, such as a list.

Using Array.enumerated() is useful when you want to keep track of the index of the elements of an iterable.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

50 Swift Interview Questions

iOS Development Tips

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.