Using swift for loop with index values

Swift provides an easy and intuitive way to loop through a collection using a for loop. But sometimes, you may need to access the index of the current element in the loop. In such cases, you can use the enumerated() method to get the index along with the element. In this article, we’ll explore how to use Swift for loop with index values.

Let’s start with a simple example. Suppose you have an array of numbers and you want to print each number along with its index. Here’s how you can do it using the enumerated() method:

let numbers = [10, 20, 30, 40, 50]

for (index, number) in numbers.enumerated() {
    print("Number at index \(index) is \(number)")

The enumerated() method returns a sequence of pairs, where each pair contains the index and the element at that index. The for loop then iterates through this sequence and assigns the index and the element to the variables index and number, respectively.

You can also use the for in loop with the stride() method to iterate over a range of indices. The stride() method allows you to specify the starting and ending indices as well as the step size. Here’s an example:

let fruits = ["apple", "banana", "orange", "pear"]

for i in stride(from: 0, to: fruits.count, by: 2) {
    print("Fruit at index \(i) is \(fruits[i])")

In this example, we’re using the stride() method to loop through the even indices of the fruits array. The from: parameter specifies the starting index (0), the to: parameter specifies the ending index (fruits.count), and the by: parameter specifies the step size (2).

If you want to loop through the array in reverse order, you can use the reversed() method. Here’s an example:

let colors = ["red", "green", "blue", "yellow"]

for (index, color) in colors.reversed().enumerated() {
    print("Color at index \(colors.count - 1 - index) is \(color)")

In this example, we’re first calling the reversed() method to reverse the order of the colors array. We’re then calling the enumerated() method to get the index and the color. Since the reversed() method changes the order of the array, we need to calculate the actual index by subtracting the current index from the total number of elements (colors.count - 1 - index).

In conclusion, using the enumerated() method, the stride() method, and the reversed() method, you can easily loop through a collection and access the index of the current element. This can be useful in many situations where you need to perform some operation on the element based on its index.

A pat on the back !!


Join group of Software Professionals