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.
- What is an Optional in Swift, and what is it internally?
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… - Why can
switchon an Optional use.none/.someand alsonil?
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.
if letvsguard letvs??vs force unwrap — when is each one OK?
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…- What does
guardbuy you beyondif?
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.
- What is the difference between
if case,guard case, andswitchon an enum?
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.
- How does optional chaining (
a?.b?.c) actually work?
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… - What is
flatMapvsmaponOptional? What aboutOptional.mapvs arraymap?
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
- 1.1 · Value vs reference types
- 1.3 · Protocols, extensions, associated types
- 1.4 · Generics, <code>some</code>, <code>any</code>
- 1.5 · Closures, escaping, capture lists
- 1.6 · Properties, observers, wrappers
- 1.7 · Access control
- 1.8 · Error handling, <code>defer</code>, ownership
- 1.9 · Strings and Unicode
- 1.10 · Codable, Sendable, macros, ABI
- 1.11 · Static vs dynamic dispatch