I want to iterate over an arbitrary Swift collection and get both the element and its index.
Basically an alternative to:
for (idx, el) in collection.enumerate() {
print("element at \(idx) is \(el)")
}
but that gives me real generic indexes, not just sequential integers starting at 0.
Of course, the solution is going to be a part of a generic function that accepts any kind of collection, otherwise the difference wouldn't be very important.
Is there a better way than a naïve loop like below?
var idx = collection.startIndex, endIdx = collection.endIndex
while idx < endIdx {
let el = collection[idx]
print("element at \(idx) is \(el)")
idx = idx.successor()
}
Writing that seems fairly error-prone. I know I can turn that code into a snippet, but I'd like to find a more concise and more idiomatic solution if possible.