Choosing where a loop starts and ends
A Swift for-in loop goes through the values of a range, so the numbers it visits are decided by the range you write. Changing the start and the end of the range changes what the loop prints. For example, all numbers from 2 through 6:
for i in 2..<7 {
print(i)
}
The output is:
2
3
4
5
6
The range 2..<7 starts at 2 and stops before 7. The same numbers can be written with a closed range, 2...6, which includes its last value. Both ranges hold exactly the same five numbers, so both loops print the same thing.
Half-open or closed
The two operators differ only in the end value:
| Range | Values | Count |
|---|---|---|
3..<10 | 3, 4, 5, 6, 7, 8, 9 | 7 |
3...10 | 3, 4, 5, 6, 7, 8, 9, 10 | 8 |
Use ... when the last number is part of the task ("from 3 through 10"). Use ..< when you think in terms of a count or a length, as in 0..<n. Both forms step by 1, and the loop variable goes up by one on each pass.
Variables as bounds
The ends of a range can be any Int expressions, not just literals, and the loop variable can be used in calculations inside the body:
let first = 2
let last = 6
for i in first...last {
print(i * i)
}
This prints the squares 4, 9, 16, 25 and 36, one per line. The range is built once, when the loop starts. If the bounds were var variables, changing them inside the body would not change how many times the loop runs.
The exercise: numbers 3 through 10
The task is to print every number from 3 to 10, with 10 included. It is built in two steps.
- Write a
for-inloop withiover3...10. The task says "through 10", so the closed range is the direct match. It holds 3, 4, 5, 6, 7, 8, 9 and 10. - Print
iinside the loop.printends its output with a newline, so each number appears on its own line.
for i in 3...10 {
print(i)
}
The output starts with 3 and ends with 10, eight lines in all.
The half-open range 3..<11 prints the same numbers, because it stops before 11. Both are correct, and the closed range is easier to read when the task mentions the last number.
Common mistakes
- Stopping one number early.
3..<10ends at 9, so 10 is never printed. - Starting at the wrong place. A loop over
0...10would print 0, 1 and 2 as well. - Reversing the bounds. A range whose start is above its end, such as
10...3, is not valid and crashes at run time. A loop that counts down is written withstride, which is the topic of the lessons that follow. - Looking for a step. A range always moves by 1. To move in other steps, you need
stride.
Key takeaways
- The start and end of the range decide which numbers a
for-inloop visits. a...bincludesbanda..<bleaves it out.for i in 3...10prints 3 through 10.- Ranges step by 1; other steps need
stride.
