← Back to Swift Course | Chapter 3: Control Flow | Lesson 4 of 8

The for-in Loop

A for-in loop lets you repeat some code once for every item in a list, like reading every name on a roster one by one.

Iterating Over a Range

A for-in loop can iterate over a numeric range, running the body once for each value in that range.

Example: Iterating Over a Range

markup
for i in 1...5 {
    print("Count: \(i)")
}

Iterating Over an Array

The same for-in syntax works directly over an array, giving you each element in order.

Example: Iterating Over an Array

markup
let fruits = ["apple", "banana", "cherry"]
for fruit in fruits {
    print("Fruit: \(fruit)")
}

Half-Open vs Closed Ranges

..< creates a half-open range that excludes its upper bound, while ... creates a closed range that includes it -- an important distinction when looping over array indices.

Note: 0..<numbers.count is the idiomatic way to loop over valid indices without going out of bounds.

Example: Half-Open vs Closed Ranges

markup
let numbers = [10, 20, 30]
for index in 0..<numbers.count {
    print("Index \(index): \(numbers[index])")
}
Common Mistakes
  1. Using a C-style for i = 0; i < n; i++ loop; that syntax was removed from Swift entirely -- use for i in 0..<n instead.
  2. Confusing the closed range ... (includes both ends) with the half-open range ..< (excludes the upper end).
  3. Trying to modify the loop variable inside the loop body expecting it to affect iteration; the loop variable is a fresh constant each iteration.
Chapter Summary
  • for item in collection iterates over every element of an array, range, dictionary, or other sequence.
  • 0..<5 is a half-open range excluding 5; 0...5 is closed and includes 5.
  • The loop variable is a constant by default, freshly bound each iteration.
  • for-in works on arrays, ranges, strings, dictionaries, and any type conforming to Sequence.
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 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.