Iterating Over Collections
Iterating means visiting every single item in a collection, one after another, usually to do something with each one.
In this page:
Iterating an Array with enumerated()
.enumerated() pairs each element with its index, letting you access both together inside a for-in loop.
Example: Iterating an Array with enumerated()
let colors = ["red", "green", "blue"]
for (index, color) in colors.enumerated() {
print("\(index): \(color)")
}
Login to try C/C++/Java/PHP code in the editor
Iterating a Dictionary
Iterating a dictionary directly with for-in gives you a tuple of (key, value) for each entry, which can be destructured right in the loop header.
Example: Iterating a Dictionary
let ages = ["Alice": 30, "Bob": 25]
for (name, age) in ages {
print("\(name) is \(age)")
}
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting that iterating a dictionary gives
(key, value)tuples, not just values. - Using an index-based loop when a direct
for-inover the collection's elements would be simpler and safer. - Not knowing
.enumerated()exists, and manually tracking an index counter variable instead.
Chapter Summary
for-initerates directly over an array's elements, a set's members, or a dictionary's key-value pairs..enumerated()provides both the index and the element together while iterating an array.- Iterating a dictionary yields tuples that can be destructured into separate key and value constants.
- Sets iterate in an unspecified order, unlike arrays which preserve insertion order.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: