← 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.
Syntax
swift
for item in collection {
    // use item
}

for i in 1...5 { }      // closed range
for i in 0..<count { }  // half-open range

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
// Loop over `1...5`, binding each item to `i`
for i in 1...5 {
    // Print "Count: \(i)" to the console
    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
// Declare a constant `fruits`, set to `["apple", "banana", "cherry"]`
let fruits = ["apple", "banana", "cherry"]
// Loop over `fruits`, binding each item to `fruit`
for fruit in fruits {
    // Print "Fruit: \(fruit)" to the console
    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
// Declare a constant `numbers`, set to `[10, 20, 30]`
let numbers = [10, 20, 30]
// Loop over `0..<numbers.count`, binding each item to `index`
for index in 0..<numbers.count {
    // Print "Index \(index): \(numbers[index])" to the console
    print("Index \(index): \(numbers[index])")
}
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. 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.