typestar

if let and guard let in Swift

Unwrap by shadowing: same name, non-optional inside.

func report(entry: String?) {
    // guard let unwraps for the rest of the function, or bails.
    guard let entry else {
        print("No entry logged")
        return
    }
    print("Logbook: \(entry)")
}

let winds: [String: String] = ["morning": "SW 12"]

// if let unwraps for one block; the shadowed name is non-optional.
if let noon = winds["noon"] {
    print("Noon wind \(noon)")
} else if let morning = winds["morning"] {
    print("Falling back to morning: \(morning)")
}

report(entry: "rounded the pin early")
report(entry: nil)

How it works

  1. guard let entry else unwraps for the whole function or exits.
  2. if let noon = winds["noon"] unwraps for one block.
  3. The else-if ladder tries fallbacks in order.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
503
Tokens
111
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 102 seconds.

Type this snippet

Step 2 of 3 in Optionals, step 11 of 27 in Language basics.

← Previous Next →