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.

  1. throws vs Result vs optional — when do you use each? 1.8.1 · L1
    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…
  2. try, try?, try! — and what is rethrows? 1.8.2 · L2
    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…
  3. What are typed throws (throws(MyError))? Why do they exist? 1.8.3 · L3
    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.

  1. What does defer guarantee? What is the order of multiple defers? 1.8.4 · L2
    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.

  1. What are consume, borrowing, and noncopyable types, at a high level? 1.8.5 · L5
    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