← 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.
Syntax
swift
for (index, element) in array.enumerated() {
    // index and element
}

for (key, value) in dictionary {
    // each pair
}

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
// Declare a constant `colors`, set to `["red", "green", "blue"]`
let colors = ["red", "green", "blue"]
for (index, color) in colors.enumerated() {
    // Print "\(index): \(color)" to the console
    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
// Declare a constant `ages`, set to `["Alice": 30, "Bob": 25]`
let ages = ["Alice": 30, "Bob": 25]
for (name, age) in ages {
    // Print "\(name) is \(age)" to the console
    print("\(name) is \(age)")
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
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.