While Loop in Swift

Level 257 keystrokes

Uses a while loop to count down from 3 to 1, printing "Countdown: n" each time.

Swift code

// The counter must be var because it changes in the loop
1var n = 3
// The condition is checked before each pass; the loop stops when n reaches 0
2while n > 0 {
// Prints Countdown: 3, then 2, then 1
3 print("Countdown: \(n)")
// Decrease n by 1 (Swift has no -- operator)
4 n -= 1
5}

Output

Countdown: 3
Countdown: 2
Countdown: 1
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Swift code and how often they appear.

  • "× 2
  • (× 2
  • )× 2
  • =× 2
  • -× 1
  • :× 1
  • {× 1
  • }× 1
  • \× 1
  • >× 1

More Swift examples at level 2

← Swift typing practice