Swift has no C-style for loop, so how do you write counted, stepped, filtered and run-at-least-once loops instead?
answer
- removed in Swift 3
- for-in walks any Sequence
- to stops short, through may land
- where skips a pass
- condition checked after the body
basics
~20 sSwift loops with for-in over a sequence: a range to count, stride(from:to:by:) or stride(from:through:by:) to step, and a where clause to skip passes. while checks before each pass; repeat-while checks after, so its body runs at least once.
solid answer
~50 sThe C-style `for var i = 0; i < n; i += 1` was removed in Swift 3, and the compiler now says "C-style for statement was removed in Swift 3". Counting uses `for i in 0..<n`. Stepping uses the standard-library `stride` functions: `stride(from:to:by:)` never includes the end value, while `stride(from:through:by:)` includes it only if whole steps land on it - `stride(from: 0, through: 10, by: 3)` yields 0, 3, 6, 9. A negative step counts down, a step pointing away from the end yields nothing, and a zero step traps. `for x in seq where condition` runs the body only for elements that pass, without ending the loop. `while` tests its condition before every pass, so it can run zero times; `repeat { ... } while condition` tests after, so it always runs once.
code
swift · 19 linesprint(Array(stride(from: 0, to: 10, by: 3))) // [0, 3, 6, 9]
print(Array(stride(from: 0, through: 9, by: 3))) // [0, 3, 6, 9]
print(Array(stride(from: 0, through: 10, by: 3))) // [0, 3, 6, 9]
print(Array(stride(from: 10, to: 0, by: -4))) // [10, 6, 2]
print(Array(stride(from: 0, to: 10, by: -1))) // []
for minute in stride(from: 0, to: 60, by: 15) where minute != 30 {
print("slot", minute) // 0, 15, 45
}
var attempts = 0
repeat {
attempts += 1
} while attempts < 0
print("repeat ran", attempts) // 1
attempts = 0
while attempts < 0 { attempts += 1 }
print("while ran", attempts) // 0go deeper
Recall that the C-style for loop is gone, that for-in walks ranges and stride sequences, and that repeat-while always runs its body once.
Explain the exact bounds of stride(from:to:by:) versus stride(from:through:by:), including a step that does not land on the end, and how where filters without stopping.
Spot loop bugs in review: off-by-one bounds, a while that should be repeat-while, a hand-managed counter that a stride would state more clearly.
There is no design decision here beyond consistency; expect leads to ask for the loop form that states its bounds and exit most directly.
## for-in walks any sequence Swift's `for` loop exists only in the `for`-`in` form, and it is not tied to integers. The loop calls `makeIterator()` on whatever follows `in` - anything that conforms to `Sequence` - and then calls `next()` on that iterator before every pass. When `next()` returns `nil`, the loop ends. Arrays, sets, dictionaries, strings, ranges and the `stride` sequences all work the same way. The C-style loop with an initializer, a condition and an increment was removed in **Swift 3** (proposal SE-0007). Writing one today fails at parse time: ```plaintext error: C-style for statement was removed in Swift 3 ``` Two small habits follow from the iterator model: - Write `for _ in 1...3` when the body does not need the loop value; the compiler warns about a named constant that is never used. - The loop variable is a new `let` constant on every pass, so `i += 1` inside the body fails with "left side of mutating operator isn't mutable: 'i' is a 'let' constant". Writing `for var i in ...` makes it mutable, but the next pass still starts from the next element, so it is never a way to skip ahead. ## Counting and stepping: ranges and `stride` A half-open range `0..<n` runs `n` times starting at zero; a closed range `1...n` includes `n`. (Range operators and what happens with a reversed range are covered in the Swift lesson on operators and ranges.) For any step other than one, use the two global `stride` functions from the standard library's `Stride.swift`: | Function | End value | Example | Values | |---|---|---|---| | `stride(from:to:by:)` | never included | `stride(from: 0, to: 10, by: 3)` | 0, 3, 6, 9 | | `stride(from:through:by:)` | included only if a whole number of steps reaches it | `stride(from: 0, through: 9, by: 3)` | 0, 3, 6, 9 | | `stride(from:through:by:)` | not reached exactly | `stride(from: 0, through: 10, by: 3)` | 0, 3, 6, 9 | The doc comments spell out the edge cases: - A **negative** `by:` counts downward: `stride(from: 10, to: 0, by: -4)` gives 10, 6, 2. - A step that **moves away** from the end produces an empty sequence: `stride(from: 0, to: 10, by: -1)` runs the body zero times. - A step of **zero** traps at run time with "Stride size must not be zero". - `stride` works for any `Strideable` type, so `stride(from: 0.0, through: 1.0, by: 0.25)` yields five `Double` values. ## Filtering with `where` A `where` clause after the sequence runs the body only for elements whose condition is true. It filters; it does not stop the loop: ```swift for minute in stride(from: 0, to: 60, by: 15) where minute != 30 { print("slot", minute) // 0, 15, 45 } ``` This is equivalent to an `if` or a `guard ... else { continue }` at the top of the body, and reads better when the filter is the whole point. A condition that should end the loop needs `break` instead. ## `while` and `repeat`-`while` Both loops repeat while a condition stays true; they differ only in when the condition is tested. 1. `while condition { ... }` evaluates the condition **first**. If it is false at the start, the body never runs. 2. `repeat { ... } while condition` runs the body **first** and evaluates the condition after each pass, so the body runs **at least once**. It is the loop for "try, then decide whether to try again". ```swift var attempts = 0 repeat { attempts += 1 // runs once even though the condition is false } while attempts < 0 ``` A `while` condition can also be an optional binding, which makes `while let next = queue.popLast() { ... }` a compact way to drain a stack until it is empty. The `repeat`-`while` condition, by contrast, is a single Boolean expression and cannot bind. ## Choosing the form | Need | Form | |---|---| | Every element of a collection | `for item in items` | | A count of passes | `for i in 0..<n` | | Steps other than one, or counting down | `for i in stride(from:to:by:)` or `stride(from:through:by:)` | | Skip some elements | `for item in items where condition` | | Unknown number of passes, test first | `while condition` | | At least one pass, test afterwards | `repeat { } while condition` | ## Mistakes that show up in review - Assuming `stride(from:through:by:)` always yields the end value; it does so only when the steps land on it exactly. - Expecting a `where` clause to stop the loop at the first element that fails it. - Reaching for `while` with a hand-managed counter where `for i in stride(...)` states the bounds in one line. - Using `while` for a retry that must happen at least once, then duplicating the body before the loop.
- What happens if you pass zero as the by: argument of stride(from:to:by:)?The program traps at run time with the precondition message "Stride size must not be zero". A zero step would never reach the end, so the standard library stops the program instead of looping forever. A step pointing away from the end is different: it is legal and simply yields an empty sequence.
- How would you count down from 10 to 1 inclusive in Swift?Either `for i in stride(from: 10, through: 1, by: -1)`, which reads as the bounds you mean, or `for i in (1...10).reversed()`, which reverses a closed range. Both yield 10 down to 1; `stride` also handles steps other than one.
- stride(from:through:by:) always includes the end value
- repeat-while checks its condition before the first pass
- Swift still accepts for var i = 0; i < n; i += 1
- A where clause on for-in stops the loop at the first false
- A stride that moves away from its end loops forever