Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Control Flow  ›  Lesson

for-in Loops

for 12 minA for-in loop runs its body once for each item in a range, list or stride, with closed ranges including the end and half-open ranges stopping before it.

for-in Loops

Sprout's weekly view draws seven little circles, one per day, and its list shows a row for every habit. Anything that repeats "once for each" is a for-in loop, and in SwiftUI the same idea draws every row of a list.

The rule

for item in collection: one pass per item, in order.

Loop over a range of numbers:

for day in 1...7 {
    print("Day \(day)")          // Day 1 ... Day 7
}

1...7 is a closed range: it includes both ends, so the body runs seven times. 0..<7 is a half-open range: it stops before 7, which suits counting from zero.

Loop over a list (an array) of values:

let habits = ["Read", "Walk", "Stretch"]
for habit in habits {
    print("Did you \(habit.lowercased()) today?")
}

Useful variations:

  • Need the position too? for (index, habit) in habits.enumerated() gives 0 and "Read", then 1 and "Walk", and so on.
  • Do not need the value at all? for _ in 1...3 { print("🌱") } runs three times.
  • Need steps other than one? for minute in stride(from: 0, to: 60, by: 15) gives 0, 15, 30, 45. Using through: 60 would include 60 as well.

The loop name (day, habit) is a new constant for each pass. You cannot change it inside the body, and it does not exist after the loop.

The shortcut

Count the passes before reading the body. For a...b it is b - a + 1; for a..<b it is b - a; for a list it is the list's count. Then check the edges: does the last pass include the end or not?

Sprout's reminder slotsStep 1 of 4
  1. The loop

    for hour in stride(from: 8, to: 20, by: 4) schedules a reminder each pass.

The trap is 0...habits.count: it runs one pass too many and reading habits[habits.count] crashes. Use 0..<habits.count, or better, loop over habits directly.

Drills

Answer fast — trust the rule.

quick drill

How many times does for i in 0..<5 run?

quick drill

How many times does for d in 3...7 run?

quick drill

What does for (i, h) in ["Read", "Walk"].enumerated() { print(i, h) } print first?

quick drill

Which values does stride(from: 0, through: 30, by: 10) give?

Remember

  • for item in collection: one pass per item, in order.
  • Count passes first: a...b is b − a + 1, a..<b is b − a.
  • Loop over the list itself instead of indexes when you can.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainCount the passes

Explain how many times each loop runs and which values it sees: for d in 1...7, for i in 0..<habits.count with three habits, and for m in stride(from: 0, to: 60, by: 20).