Chapter 6: Optionals

大綱

Introducing nil

  • it’s useful to represent the absence of a value

Sentinel values

  • it’s useful to represent the absence of a value

    • 0 is a sentinel value.

  • Nil is the name given to the absence of a value, and you’re about to see how Swift incorporates this concept directly into the language in a rather elegant way.

Introducing optionals

  • Optionals are Swift’s solution to the problem of representing both a value and the absence of a value

Unwrapping optionals

Force unwrapping

  • you get this error at runtime rather than compile time

  • if this code were inside an app, the runtime error would cause the app to crash

Optional binding

  • You can combine unwrapping multiple optionals with additional Boolean checks

Introducing guard

Nil coalescing

Key points

  • nil represents the absence of a value.

  • Non-optional variables and constants must always have a non-nil value.

  • Optional variables and constants are like boxes that can contain a value or be empty (nil).

  • To work with the value inside an optional, you must first unwrap it from the optional.

  • The safest ways to unwrap an optional’s value is by using optional binding or nil coalescing.

  • Use forced unwrapping only when appropriate, as it could produce a runtime error.

Last updated