1.8 · Error handling, <code>defer</code>, ownership
Swift separates “this failed” from “this is absent”. throws is for failure, Result is for storing an outcome, and Optional is for absence — three different messages.
Mental model. throws = control flow. Result = a value. T? = “there is nothing here”, which is not an error until you decide it is.
Throwing and catching
Choosing how failure is reported.
throwsvsResultvs optional — when do you use each?
throws — typed failure at a function boundary. The caller must try, and the failure is handled at the point of the call. Best for user-initiated work where you…try,try?,try!— and what isrethrows?
try propagates the error to the caller. try? converts any error to nil and success to an optional — the error itself is discarded. try! crashes if an error is…- What are typed throws (
throws(MyError))? Why do they exist?
Swift 6 makes the thrown type part of the function type: func load() throws(ParseError) -> Data. Callers can catch exhaustively over an enum, and generics can…
Cleanup with defer
Code that runs however the scope exits.
- What does
deferguarantee? What is the order of multipledefers?
defer runs when the current scope exits — by return, throw, break, or falling off the end. It runs even on the error path, which is why it is the right place…
Ownership
Values that move instead of copying.
- What are
consume,borrowing, and noncopyable types, at a high level?
Ownership annotations express move vs read: consume ends a value's life (it is moved, not copied); borrowing grants read access without a copy. ~Copyable types…
More in Swift language
- 1.1 · Value vs reference types
- 1.2 · Optionals, pattern matching, control flow
- 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.9 · Strings and Unicode
- 1.10 · Codable, Sendable, macros, ABI
- 1.11 · Static vs dynamic dispatch