Iterate over items and indices in Swift collections
I used enumerated() before without giving it too much thought when I needed to get items and indices in Swift collections. But it's actually not the right way to do it.
The integer value we get with enumerated()
isn’t a real index into the collection unless the collection is zero-based and integer-indexed. It’s just a counter that always starts from zero.
var ingredients = ["potatoes", "cheese", "cream"]
for (i, ingredient) in ingredients.enumerated() {
// do something with the counter number
print("ingredient number \(i + 1) is \(ingredient)")
}
To iterate over items and indices we can use the zip() function instead.
// Array<String>
var ingredients = ["potatoes", "cheese", "cream"]
// Array<String>.SubSequence
var doubleIngredients = ingredients.dropFirst()
for (i, ingredient) in zip(
doubleIngredients.indices, doubleIngredients
) {
// do something with the index
doubleIngredients[i] = "\(ingredient) x 2"
}
We can even avoid using enumerated()
completely and count items with zip()
as well. That way, we can decide whether we want to start counting from 0
or from 1
.
var ingredients = ["potatoes", "cheese", "cream"]
for (i, ingredient) in zip(1..., ingredients) {
// do something with the counter number
print("ingredient number \(i) is \(ingredient)")
}
For a nicer interface over zip()
, we can also use indexed() from Swift Algorithms. It’s equivalent to zip(doubleIngredients.indices, doubleIngredients)
, but might be more readable.
import Algorithms
// Array<String>
var ingredients = ["potatoes", "cheese", "cream"]
// Array<String>.SubSequence
var doubleIngredients = ingredients.dropFirst()
for (i, ingredient) in doubleIngredients.indexed() {
// do something with the index
doubleIngredients[i] = "\(ingredient) x 2"
}
These examples come from a thread on X I started, which ended up collecting lots of interesting tips and discussions from different people. You can give it a read if you like.
As someone who has worked extensively with Swift, I've gathered many insights over the years and compiled them in my book, Swift Gems. The book focuses exclusively on the Swift language and Swift Standard Library, offering over 100 advanced tips and techniques on topics such as optimizing collections, leveraging generics, asynchronous programming, and debugging. Each tip is designed to help intermediate and advanced Swift developers write clearer, faster, and more maintainable code by fully utilizing Swift's built-in capabilities.