All lessons

Loops

7 min · Swift

Repeat work without writing it out a hundred times.

Swift · Loops0/5 cleared

Enemy 1 of 5

This loop runs its body three times, and i counts 0, 1, 2. The range 0..<3 stops before 3. Press Run to see the three numbers printed.

Why this works

Loops let you repeat a block of code without writing it out by hand every time. Swift's for loop walks over a range of values: for i in 0..<3 { ... } runs its body three times, with i taking the values 0, then 1, then 2 in turn.

The ..< operator is a half-open range: it includes the starting value (0) but excludes the ending value (3). This matches Rust's 0..3 exactly, and it's genuinely convenient once it clicks, the number of iterations is simply the end minus the start, with no mental "plus or minus one" adjustment needed. Swift also has a fully closed range operator, ... (three dots, no less-than sign), which includes both ends: 1...5 covers 1, 2, 3, 4, and 5. Mixing up ..< and ... is a classic source of off-by-one bugs, so pay close attention to which one a piece of code uses.

Compared to a classic C-style for (int i = 0; i < 3; i++) loop, Swift's for i in 0..<3 reads closer to plain English, and there's no separate condition or increment step to get wrong: the range fully describes what values i will take.

You
Invisible Heisenbug
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.