Guard Statement in Swift

Level 2120 keystrokes

Uses guard let to unwrap an optional parameter and leave the function early when it is nil; greet("Swift") prints "Hello, Swift!".

Swift code

// _ removes the argument label; the parameter is an optional String
1func greet(_ name: String?) {
// If name is nil, the else block runs; otherwise n holds the String
2 guard let n = name else {
3 print("No name")
// The else block of guard must leave the scope (return, throw, …)
4 return
5 }
// Unlike if let, n stays available after the guard: Hello, Swift!
6 print("Hello, \(n)!")
7}
// A String is passed, so it is wrapped in an optional automatically
8greet("Swift")

Output

Hello, Swift!
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.

  • "× 6
  • (× 5
  • )× 5
  • {× 2
  • }× 2
  • _× 1
  • ,× 1
  • :× 1
  • !× 1
  • ?× 1

More Swift examples at level 2

← Swift typing practice