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. Usingthrough: 60would 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?
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.
How many times does for i in 0..<5 run?
How many times does for d in 3...7 run?
What does for (i, h) in ["Read", "Walk"].enumerated() { print(i, h) } print first?
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...bis b − a + 1,a..<bis b − a. - Loop over the list itself instead of indexes when you can.
