Guard Statement in Swift

Level 280 keystrokes

Uses guard to return early when the number is not positive, so check(5) prints 5 and check(-1) prints nothing.

Swift code

// _ means callers pass the argument without a label
1func check(_ n: Int) {
// guard requires the condition to be true; otherwise else runs and returns
2 guard n > 0 else { return }
// Reached only when n > 0
3 print(n)
4}
// 5 passes the guard and is printed: 5
5check(5)
// -1 fails the guard, so the function returns without printing
6check(-1)

Output

5
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.

  • (× 4
  • )× 4
  • {× 2
  • }× 2
  • _× 1
  • -× 1
  • :× 1
  • >× 1

More Swift examples at level 2

← Swift typing practice