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 String1func greet(_ name: String?) { // If name is nil, the else block runs; otherwise n holds the String2 guard let n = name else {3 print("No name") // The else block of guard must leave the scope (return, throw, …)4 return5 } // 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 automatically8greet("Swift")Output
Hello, Swift!
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