Iterate a loop with both index and element in Swift

When working with loops in Swift, it’s often useful to have access to both the index and the element at the same time. This can be achieved using a for-in loop with the enumerated() method. Here’s an example:

let array = ["apple", "banana", "cherry"]

for (index, element) in array.enumerated() {
    print("Index: \(index), Element: \(element)")
}

This will output:

Index: 0, Element: apple
Index: 1, Element: banana
Index: 2, Element: cherry

As you can see, the enumerated() method returns a sequence of tuples, where each tuple contains the index and element of the array. We can then use tuple decomposition to extract these values in the loop.

This approach can be used with any sequence type in Swift, including arrays, dictionaries, and ranges. Here’s an example with a dictionary:

let dict = ["a": 1, "b": 2, "c": 3]

for (key, value) in dict.enumerated() {
    print("Key: \(key), Value: \(value)")
}

This will output:

Key: 0, Value: ("a", 1)
Key: 1, Value: ("b", 2)
Key: 2, Value: ("c", 3)

In this case, the enumerated() method returns a sequence of tuples, where each tuple contains the index and key-value pair of the dictionary. We can then use tuple decomposition to extract the key and value in the loop.

Overall, using for-in loops with the enumerated() method is a simple and effective way to iterate through a sequence in Swift while also accessing the index and element values at the same time.

A pat on the back !!