Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 146 ยท Control Flow

Optionals

Understand Swift optionals from scratch - what nil means, if let and guard let unwrapping, nil coalescing, optional chaining, force unwrapping and why it crashes.

What should Int("hello") return? The text is not a number, so there is no right integer to give back. Older languages answer with a magic value (-1, 0, NaN), with null, or with an exception, and each of those has caused countless bugs: the magic value looks like a real answer, null is invisible in the type, and exceptions are easy to forget. Swift's answer is the optional. An optional is a value that either holds something or holds nothing, and the type system makes you deal with both cases before you can use the contents.

This is probably the most important feature of Swift's design. After this lesson you will know what String? means, how to open an optional safely with if let, guard let, ?? and optional chaining, and why ! is a loaded gun. The next lesson, Optionals in Depth, covers map, flatMap and more advanced patterns.

What an optional is

Add a question mark to any type to make it optional: Int? means "either an Int, or nothing". The "nothing" is written nil.

Swift Optionals from parsing

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 integer initializer that takes text is failable: it returns Int?, because parsing can fail. Printing an optional shows Optional(42) or nil, and the type is Optional<Int>, written Int? for short. That reveals what an optional really is: an ordinary enum with two cases, .none (written nil) and .some(value).

Swift
// Simplified definition from the standard library
enum Optional<Wrapped> {
    case none
    case some(Wrapped)
}

This matters because it means there is no hidden magic: nil is not a special pointer value you can stumble into. A plain Int can never be nil. Only types you mark with ? can, and the compiler tracks which is which.

Swift optionals are the reason "null pointer exceptions" practically disappear from well-written Swift code. The question "can this be missing?" is answered in the type, and the compiler enforces the answer everywhere.

The compiler makes you unwrap

You cannot use an optional where the plain type is expected, because the value might not be there. Try adding an optional Int to a number:

Swift Using an optional as a plain value (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 error is value of optional type 'Int?' must be unwrapped to a value of type 'Int', with several fix-it suggestions: provide a default with ??, or force-unwrap with !. The sections below show every way out, ordered from safest to most dangerous.

Optional binding: if let

if let checks whether the optional contains a value and, if so, gives you a plain constant to use inside the block:

Swift if let and else

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.

if let name = optionalName creates a new constant name that exists only inside the braces. When the new name would be the same as the old one, write if let optionalName (Swift 5.7). You can list several bindings and boolean conditions separated by commas; the block runs only if all succeed. You can also use var instead of let if you need to modify the unwrapped value, though a let is usually better.

Early exit: guard let

When missing data means "stop here", guard let unwraps and leaves the scope on failure, and the constant stays available afterwards. We covered it in guard and Early Exit; in short, use guard let to avoid nesting.

Swift
func greet(_ name: String?) {
    guard let name else {
        print("hello, stranger")
        return
    }
    print("hello, \(name)")
}

A default value: ??

The nil-coalescing operator ?? unwraps the optional on its left or, if it is nil, gives the value on its right. It is the shortest way to say "use this, or else that".

Swift Nil coalescing

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 right-hand side of ?? is an autoclosure, so it is only evaluated if the left side is nil. In the first print above, "computing the default..." never appears. Dictionary lookups return optionals (a key might be missing), so dict[key] ?? default is very common; there is also the form dict[key, default: 0] that avoids the optional entirely (see Dictionaries).

Be careful that a default can hide an error. Int(userInput) ?? 0 quietly turns "the user typed garbage" into "zero". Use ?? when a default is truly meaningful, not to silence the compiler.

Optional chaining: ?.

Often you only want to call a method or read a property if the optional has a value, and otherwise get nil back. Put ? after the optional:

Swift Optional chaining

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.

If anything in the chain is nil, the rest is skipped and the whole expression is nil. The result type is always optional: ada.address?.city is a String?, even though city itself is a plain String. Because the chain short-circuits, you can write long accesses without a pyramid of if let. (trimmingCharacters(in:) comes from Foundation, so the example imports it; without the import the compiler says value of type 'String' has no member 'trimmingCharacters'.) See Optional Chaining in Depth for assignment through a chain and chains across methods and subscripts.

Force unwrapping: !

Putting ! after an optional says "I promise there is a value; give it to me". If you are wrong, the program crashes.

Swift Force-unwrapping nil (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 run ends with an illegal-instruction signal (SIGILL) and a backtrace, because our runner compiles with optimizations, which strip the message. A debug build stops with a fatal error that says it unexpectedly found nil while unwrapping an Optional value. Either way the program stops on the spot. ! is occasionally justified, when the value is guaranteed by something the compiler cannot see, like a hard-coded literal known to be valid:

Swift
let secondsPerDay = Int("86400")!        // a constant we control

Even then, a safer pattern exists in most cases. In tutorials and quick scripts ! is fine; in app code each ! is a decision you must be able to defend. A code review rule many teams use: every force unwrap needs a comment explaining why it cannot fail. If you want a clear crash with a clear message instead, use guard let ... else { fatalError("...") }.

try? and other places optionals appear

Optionals show up everywhere in the standard library, so it helps to recognize them:

  • Failable initializers: Int("7"), URL(string: "..."), Double("3.5").
  • Collection queries: array.first, array.last, array.max(), dictionary[key], array.firstIndex(of: x).
  • Casting: value as? Int.
  • Converting errors: try? turns a throwing call into an optional (see Error Handling).
  • Absent properties in your own types: var middleName: String?.

One more useful detail: a variable of optional type is automatically nil when declared without a value, so var x: Int? starts as nil. A constant gets no such default and must be given a value (possibly nil) before it is used.

Comparing optionals

Optionals can be compared with == when their wrapped type is Equatable (but not with <, because Optional is not Comparable). A nil is equal only to nil, and Optional(3) == 3 is true, because Swift promotes the plain value to an optional for the comparison:

Swift Comparing 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.

Comparing with == nil is fine for a quick check, but if you also need the value, if let does both in one step.

Pitfalls

  • Optional of optional. let x: Int?? = nil is valid, and distinguishes "no value" from "a value that is itself nil". It occasionally appears with try? on a throwing function that already returns an optional (Swift 5 flattens this case) or with dictionary[key] on a dictionary whose values are optional. When a type shows ??, stop and ask whether you really need both layers.
  • Optionals as booleans. There is no truthiness: if optionalInt { } does not compile. Write if optionalInt != nil or if let.
  • Printing an optional. print(optionalValue) shows Optional(42), which is almost never what a user should see. The compiler warns about it when you interpolate an optional into a string. Unwrap or use ?? "none" first.
  • Boolean optionals. A Bool? has three states: true, false and nil. Prefer a plain Bool with a default, or an enum with meaningful names.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the type of Int("12")?

    The failable initializer returns an optional, since the text might not be a number.
  2. 2. What does let n = Int("x") ?? -1 give?

    The text is not a number, so Int("x") is nil and the right-hand default is used.
  3. 3. What happens when you force-unwrap an optional that is nil?

    ! asserts that a value exists. When it does not, the runtime stops the program with a fatal error about finding nil while unwrapping an Optional value.
  4. 4. What is the type of person.address?.city if address is Address? and city is String?

    Optional chaining always returns an optional, because the chain might stop at a nil.
  5. 5. Where can you use the constant bound by if let value = optional { ... }?

    With if let, the binding is scoped to the success block. Use guard let when you need it afterwards.

Summary

  • An optional (T?) is an enum with two cases, .none (nil) and .some(value); a non-optional type can never be nil.
  • You must unwrap an optional before using its value: if let, guard let, ?? for a default, ?. for chaining.
  • if let x (Swift 5.7) is shorthand for if let x = x; several bindings and conditions can be joined with commas.
  • Optional chaining returns an optional and stops at the first nil.
  • ! force-unwraps and traps on nil (a fatal error, shown as SIGILL in our optimized runner); use it only for values you can prove exist.
  • Failable initializers, dictionary lookups, first/last and as? all return optionals.

Next: Optionals in Depth