While Loop in Swift

Level 254 keystrokes

Counts down from 3 to 1 with a while loop, then prints "Go!" after the loop ends.

Swift code

// A var counter, since it changes in the loop
1var n = 3
// Repeats while n is positive
2while n > 0 {
// Prints 3, 2, 1 in turn
3 print(n)
// Decrease n by 1; without this the loop would never end
4 n -= 1
5}
// Runs once after the loop, when n is 0: Go!
6print("Go!")

Output

3
2
1
Go!
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

More Swift examples at level 2

← Swift typing practice