#30: Iteration with Index in Swift

When you need the index and the value at the same time, enumerated() is the clearest solution:

let names = ["Ada", "Grace", "Linus"]

for (index, name) in names.enumerated() {
    print(index, name)
}

That produces zero-based integer offsets paired with each element.

If you need a real collection index instead of an integer offset, iterate over indices instead:

for index in names.indices {
    print(index, names[index])
}

That matters more for collections where the index type is not just Int.


I'm also on Twitter and GitHub.

Subscribe via RSS.