Optional Binding in Swift

Level 2105 keystrokes

Uses if let to safely unwrap an optional Int; since it holds 42, it prints "Value: 42".

Swift code

// An optional Int that currently holds 42
1let value: Int? = 42
// If value is not nil, its content is bound to unwrapped (a plain Int)
2if let unwrapped = value {
// unwrapped is only available inside this block: Value: 42
3 print("Value: \(unwrapped)")
// Runs when value is nil
4} else {
5 print("No value")
6}

Output

Value: 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.

  • "× 4
  • (× 3
  • )× 3
  • :× 2
  • {× 2
  • }× 2
  • =× 2
  • ?× 1
  • \× 1

More Swift examples at level 2

← Swift typing practice