iterate over an array with indexes in swift

You can iterate over an array with indexes in Swift using a for-in loop with the enumerated() method. Here's an example:

main.swift
let myArray = ["apple", "banana", "orange"]

for (index, value) in myArray.enumerated() {
    print("Index: \(index), Value: \(value)")
}
138 chars
6 lines

Output:

main.swift
Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: orange
71 chars
4 lines

In the loop, the enumerated() method returns a sequence of pairs (index, value) for each element in the array. The index represents the index of the element, and value represents the value of the element.

You can use the index and value variables inside the loop to perform any operations you need to do on each element of the array.

related categories

gistlibby LogSnag