0Pricing
Swift Academy · Lesson

if let and Shorthand Binding

Unwrap optionals within a scope, including Swift 5.7 shorthand.

Why Bind Optionals

An optional must be unwrapped before you can use the value inside. if let safely unwraps it only when a value exists.

let stored: Int? = 5
if let value = stored {
    print(value)
}

The if let Form

Write if let name = optional { ... }. Inside the braces, name is the unwrapped non-optional value. If the optional is nil, the block is skipped.

let input: String? = "Swift"
if let text = input {
    print(text.count)
}

All lessons in this course

  1. if let and Shorthand Binding
  2. guard let for Early Exit
  3. Binding Multiple Optionals
  4. Optional Pattern in switch and for
← Back to Swift Academy