Choosing Optionals

When a variable’s value may be undefined at any point during its lifetime, represent it with an optional type. Yes, there are other approaches for biased-value states (for example, you might create a Result type with success and error cases), so prefer optionals for simple not-yet-defined or currently undefined roles. Optionals canonically capture possibly undefined semantics.

Errors and optionals play distinct roles in Swift. Use optionals to represent the absence of a value. Throw an error to explain why something went wrong, enabling you to implement error recovery at runtime. It is not uncommon to build a function that both returns an optional and can throw an error. For example, imagine you’re looking up a filename. You’d ...

Get Swift Style now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.