Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 146 ยท Control Flow

Optionals in Depth

Go beyond if let - transform optionals with map and flatMap, fill in defaults, handle double optionals, switch over optionals, understand implicitly unwrapped optionals and avoid pitfalls.

Optionals taught you the everyday tools: if let, guard let, ??, ?. and !. They cover most code. But optionals are also a type with their own methods, and knowing those methods lets you write shorter and more precise code, especially when a value passes through several stages. This lesson looks at map and flatMap on optionals, filling in defaults, the optional pattern in switch, double optionals, compactMap, and the odd cousin called the implicitly unwrapped optional. It ends with the pitfalls that experienced Swift developers watch for.

Optional is an enum you can pattern-match

Because Optional is an enum with the cases .none and .some, you can use switch on it. The ? suffix on a pattern means ".some, and bind the content".

Swift switch over an optional

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The switch is exhaustive: nil and n? together cover everything. The pattern 0? matches .some(0); let n? matches any other .some. You will rarely write this in everyday code, because if let is shorter, but it is valuable when you want to handle several optionals together (switching over a tuple of two optionals, for instance) or combine nil handling with value ranges. See Pattern Matching for more.

map: transform the value if there is one

Imagine you have an optional string and want its length, but you want to keep "no value" as "no value". An if let works:

Swift
var length: Int? = nil
if let text = maybeText { length = text.count }

Optional.map expresses the same idea in one line. It applies a function to the wrapped value if one exists and returns an optional of the result; if the optional is nil, map returns nil without calling your closure.

Swift Optional.map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

For a method or property of the wrapped value, ?. (optional chaining) is the shortest option. map is better when you want to apply an arbitrary function or initializer: name.map(Greeting.init), text.map(String.init), or Int(text).map { $0 * 2 }. It also reads well at the end of a pipeline. Think of an optional as a box with zero or one item, and map as the "apply to what is inside, if anything" operation. Arrays, as you will see in map, filter, reduce and Friends, have the same method.

flatMap: when the function itself returns an optional

What if the transformation can also fail? Int(text) returns Int?. If you map over an optional string with Int.init, the result is Int??, an optional of an optional, which is awkward. flatMap applies the function and flattens one layer:

Swift map versus flatMap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The rule of thumb: use map when your closure returns a plain value, flatMap when it returns an optional. If you accidentally use map and see Int?? in a type, switch to flatMap. Each step in the port function is skipped as soon as something is nil; the final value is nil if any step failed. That is the railway-style flow that if let pyramids otherwise require.

A closely related tool is compactMap on sequences: it applies a function that returns an optional to every element and drops the nil results.

Swift compactMap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Filling in defaults and clearing values

Swift has no ??= operator (a mistake many people make when coming from Ruby or C#). The compiler says error: cannot find operator '??=' in scope. To fill in a default only when a value is missing, write the pattern out in one of three ways:

Swift Setting a default only when nil

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Use if x == nil { x = ... } when the default is expensive or has side effects, and x = x ?? default for a cheap value. For a value computed on first use, a lazy var property (see Properties) is the better tool than a hand-written cache. Remember also that assigning nil to a dictionary key removes the entry; this is a common surprise, and the reason a [String: Int?] dictionary needs extra care to store a real nil (see the next section).

Double optionals

Two layers of optional, T??, appear when an optional passes through something that already returns an optional. A well-known example is a dictionary whose values are optional: dict[key] then has type V??, because the outer layer says "is the key present?" and the inner one says "is the stored value nil?".

Swift Optional of optional

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

Two different kinds of "missing" are the whole story. Unless you need to tell them apart, flatten with ?? nil or flatMap { $0 }, or better, restructure the data so that the optional is not needed (for example, store only rated people).

A related detail: try? on a function that already returns an optional used to produce T?? in Swift 4, but since Swift 5 it flattens to a single T?. You get the same nil for "threw an error" and "returned nil".

Implicitly unwrapped optionals

You will sometimes see a type written with an exclamation mark, such as String!. This is an implicitly unwrapped optional (IUO). It is still an optional, but the compiler automatically force-unwraps it whenever the context requires a non-optional. If it is nil at that moment, the program traps.

Swift Implicitly unwrapped optionals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The original reason for IUOs was Objective-C interoperability and UI frameworks, where an outlet connected in an interface file is nil during init and valid afterwards. In new code, avoid them. If a property cannot be set in init, consider a lazy var, a let set in init, or a normal optional. Treat Type! as a sign that "someone promised this is set before use", and be ready for the crash if the promise is broken.

Compare how they behave when nil: an IUO that is nil and then used as a non-optional traps just like !:

Swift Using a nil IUO (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The program prints before and then stops with an illegal-instruction signal (SIGILL) on our optimized runner. In a debug build the same line ends in a fatal error saying that it unexpectedly found nil.

Optional comparison and sorting

Optional is Equatable and Hashable when its wrapped type is, so ==, Set<Int?> and dictionary keys of optional type work. It is not Comparable, so a < b does not compile for two Int? values. Decide where nil goes, then sort:

Swift Sorting optional values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readLine()), it gets the next line from this box.

The comparator matches the tuple of both values: two real numbers compare normally, a real number comes before nil, and everything else (including two nils) is "not less". For many tasks, compactMap { $0 } is simpler, because it throws the nils away first.

Pitfalls and good habits

  • Stop at the boundary. Unwrap optionals as close as possible to where they are created (the parse, the lookup) and pass plain values onward. A function that accepts String? forces every caller's reader to wonder what nil means. Prefer a non-optional parameter, and do the check in the caller.
  • Do not default away errors. Int(text) ?? 0 is fine for a hint, wrong for a payment. If the data must be valid, use guard/throw and report it.
  • Optional is not a boolean. There is no if optional. Write != nil or bind with if let.
  • Bool? has three states. Prefer a two-state Bool or an enum with named cases.
  • Optional(x) in output. Interpolating an optional gives Optional(...). Unwrap first or use ?? "none".
  • Shadowing with if let x = x is idiomatic and safe, but do not unwrap into a name that changes meaning (if let count = items?.first).
  • Avoid ! after first/last on arrays. "I know it's not empty" is true until it is not. guard let first = items.first else { return } costs one line.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Optional("hi").map { $0.count } return?

    map applies the closure to the wrapped value and wraps the result again, so the result is the optional Int? holding 2.
  2. 2. You call maybeText.map { Int($0) } and get Int??. Which method gives a flat Int??

    flatMap is for closures that already return an optional; it flattens one level.
  3. 3. With var x: Int? = nil, which line sets x to 5 only if it is still nil?

    Swift has no ??= operator. Reassigning with x ?? 5 keeps the old value when there is one and falls back to 5 when it is nil.
  4. 4. Which statement about var name: String! is true?

    An implicitly unwrapped optional is still an optional. If it is nil when a non-optional is needed, the program traps.
  5. 5. A dictionary has type [String: Int?]. What type does dict["a"] have?

    The subscript returns an optional (key present or not) of the value type, which is itself Int?. The result is a double optional.

Summary

  • Optional is an enum, so switch can match nil, value? and let x? patterns.
  • map transforms the value if present; flatMap does the same for closures that return an optional and keeps the result flat; compactMap does it for each element of a sequence and drops the nils.
  • Swift has no ??=; fill defaults with if x == nil { ... } or x = x ?? value, and remember that assigning nil to a dictionary key removes it.
  • A double optional separates "missing" from "present but nil"; flatten it with ?? nil or flatMap { $0 } when you do not need the difference.
  • Type! (an implicitly unwrapped optional) force-unwraps on demand and traps on nil; avoid it in new code.
  • Optional is Equatable but not Comparable; supply your own rule for nil when sorting.
  • Unwrap early, pass plain values, and never hide invalid data behind ?? 0.

Next: Ranges