1.2 · Optionals, pattern matching, control flow

Optionals are an enum, not a null pointer. Once you see the enum, every “gotcha” about if case, ??, and optional chaining falls out for free.

Mental model. Every T? is a two-case enum. Unwrapping is just switching on it. The syntax is sugar; the enum is the truth.

Optional is an enum

Once you see the two cases, the rest is sugar.

  1. What is an Optional in Swift, and what is it internally? 1.2.1 · L1
    Optional<Wrapped> is a plain generic enum with two cases: none and some(Wrapped). Int? is sugar for Optional<Int>, and nil is just Optional.none. Because it is…
  2. Why can switch on an Optional use .none / .some and also nil? 1.2.2 · L5
    Because Optional is an enum and pattern matching is structural. case .none and case nil are the same pattern; case .some(let x) and case let x? are the same…

Unwrapping safely

Pick the unwrap that matches what nil means here.

  1. if let vs guard let vs ?? vs force unwrap — when is each one OK? 1.2.3 · L1
    if let x { ... } binds x only inside the true branch — use it when the nil case is a normal branch among several. guard let x else { return } binds x for the…
  2. What does guard buy you beyond if? 1.2.4 · L1
    Three things: early exit, less nesting, and definite binding. After a guard, the bound values are non-optional for the remainder of the scope, so the happy…

Pattern matching

One pattern or all of them.

  1. What is the difference between if case, guard case, and switch on an enum? 1.2.5 · L2
    switch is exhaustive — the compiler requires every case (or a default/@unknown default). Use it when every case matters or when you want the compiler to tell…

Chaining and transforming

Working with values that might not be there.

  1. How does optional chaining (a?.b?.c) actually work? 1.2.6 · L2
    Each ?. checks the value on its left. If it is nil, the entire expression short-circuits to nil and later subexpressions are never evaluated. The result type…
  2. What is flatMap vs map on Optional? What about Optional.map vs array map? 1.2.7 · L3
    Optional.map transforms the wrapped value; the result is still optional. Returns T → result T?. Optional.flatMap is for closures that already return an…

More in Swift language