← Back to Swift Course | Chapter 6: Collections | Lesson 5 of 7

Iterating Over Collections

Iterating means visiting every single item in a collection, one after another, usually to do something with each one.

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()

markup
let colors = ["red", "green", "blue"]
for (index, color) in colors.enumerated() {
    print("\(index): \(color)")
}

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

markup
let ages = ["Alice": 30, "Bob": 25]
for (name, age) in ages {
    print("\(name) is \(age)")
}
Common Mistakes
  1. Forgetting that iterating a dictionary gives (key, value) tuples, not just values.
  2. Using an index-based loop when a direct for-in over the collection's elements would be simpler and safer.
  3. Not knowing .enumerated() exists, and manually tracking an index counter variable instead.
Chapter Summary
  • for-in iterates 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.