typestar

Ranges and loops in Swift

1...3 includes the end, 0..<3 stops short, stride steps.

// Closed ranges include the end; half-open ranges stop short.
for lap in 1...3 {
    print("Lap \(lap) of 3")
}
for i in 0..<3 {
    print("Start sequence: \(3 - i)")
}

// stride covers steps; while covers everything else.
for depthM in stride(from: 10, through: 2, by: -4) {
    print("Sounding: \(depthM) m")
}

var hullCheck = 3
while hullCheck > 0 {
    hullCheck -= 1
}
print("Hull clear")

How it works

  1. for lap in 1...3 iterates the closed range.
  2. 0..<3 is half-open — the collection-index shape.
  3. stride(from:through:by:) counts down by fours; while guards.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
380
Tokens
92
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 79 seconds.

Type this snippet

Step 3 of 3 in Control flow, step 6 of 27 in Language basics.

← Previous Next →

Ranges and loops in other languages