Fun with looping

I was reading the article “how to loop over arrays” over at Paul Hudsons Hacking with Swift blog, assuming I knew everything about looping over arrays. Guess what, I learned some new ways to iterate over an array!

So here’s a collection of cars:

let cars = [
    "Tesla": "Model X",
    "Lamborghini": "Aventador",
    "Smart": "fortwo"
]


Suppose we want to loop over the cars, but print the index of the car as well. My normal approach would be to use the enumerated() method.

for (index, car) in cars.enumerated() {
    print("Car \(index + 1): \(car.value) is from \(car.key)")
}

Today I learned the .indices property of a collection. How awesome!

for i in cars.indices {
    print("Car \(i.hashValue): \(cars[i].value) is from \(cars[i].key)")
}

So forget about maintaining an index yourself, use the force! Have fun with looping!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.