Optional Binding in Swift

Level 254 keystrokes

Safely unwraps an optional Int with if let and prints the value, 42.

Swift code

// Int? may hold an Int or nil; here it holds 42
1let value: Int? = 42
// The block runs only if value is not nil; num is the unwrapped Int
2if let num = value {
// Prints 42 (not Optional(42), because num is not optional)
3 print(num)
4}

Output

42
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
  • :× 1
  • ?× 1
  • (× 1
  • )× 1
  • {× 1
  • }× 1

More Swift examples at level 2

← Swift typing practice