Skip to content
LumenaryAcademy
Foundations 50 min

Optionals

A type for "maybe there is no value", and the safe ways to open it.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

The value that might not be there

Ask a program for "the first number greater than 10 in this list" and there may not be one. Convert the text "seven" to an integer and there is no sensible answer. Look up a word in a dictionary and it may be missing. Every program has to represent absence, and how a language does it shapes a whole category of bugs.

Most older languages use a special value, null or nil or None, that any reference can hold. The trouble is that the type does not tell you whether a given variable might be null, so programmers forget to check, and the program crashes far from the real mistake. Tony Hoare, who introduced null references in 1965, later called them his "billion-dollar mistake", after the cost of the crashes and security holes they caused.

Swift's answer is the optional. A String always contains a string, guaranteed. A String? (read "optional String") contains either a string or nil. They are different types, and the compiler will not let you use a String? where a String is needed until you have dealt with the nil case. The absence is written into the type, so it cannot be forgotten. This lesson is about the handful of tools Swift gives you to deal with it, and about choosing between them.

DefinitionsH

What an optional is

Definition— optional

For any type T, the type T? (in full, Optional of T) has every value of T plus one more: nil, meaning "no value". It is an ordinary enum in the standard library with two cases: .some(value), which wraps a value, and .none, which is what nil means.

You can see the difference immediately. If s is a String?, then print(s.count) does not compile: the compiler says value of optional type 'String?' must be unwrapped to refer to member 'count' of wrapped base type 'String'. Even print(s) produces a warning, and prints Optional("hi") rather than hi, a reminder that you have not decided what to do about nil.

Many standard APIs return optionals, and once you know why, you can guess which ones:

ExpressionTypenil when
Int("42")Int?the text is not a whole number
dict["key"]Value?the key is missing
array.first, array.last, array.max()Element?the array is empty
array.first(where: ...), array.firstIndex(of: x)Element?, Int?nothing matches
string.firstCharacter?the string is empty

Notice what is not on the list: array[i]. Subscripting an array returns a plain Element and traps when i is out of range, because an out-of-range index is considered a bug in your program, not an expected outcome. Swift draws this line deliberately: optionals are for absence that is a normal, expected result; traps are for mistakes.

Worked examplesH

Unwrapping, safely

if let: do something only if there is a value

swift
let typed = ["42", "7", "seven", "", "-3", "4.5"]

for text in typed {
    if let n = Int(text) {
        print("\"\(text)\" -> \(n)")
    } else {
        print("\"\(text)\" is not a whole number")
    }
}

let numbers = typed.compactMap { Int($0) }
print(numbers, numbers.reduce(0, +))

let firstBig = numbers.first(where: { $0 > 10 })
let firstHuge = numbers.first(where: { $0 > 1000 })
print(firstBig ?? -1, firstHuge ?? -1)
print(firstBig as Any, firstHuge as Any)
text
"42" -> 42
"7" -> 7
"seven" is not a whole number
"" is not a whole number
"-3" -> -3
"4.5" is not a whole number
[42, 7, -3] 46
42 -1
Optional(42) nil

if let n = Int(text) does two things at once: it tests whether the optional holds a value, and if so, binds that value to a new non-optional constant n that exists only inside the braces. This is called optional binding. Several bindings and Boolean conditions can be chained with commas, and the body runs only if all succeed: if let a = Int(x), let b = Int(y), b != 0 { ... }.

compactMap (you will meet its closure syntax properly in the next lesson) applies a transformation that may fail to every element and keeps only the successes, a very common way to clean up data. ??, the nil-coalescing operator, gives a default: firstHuge ?? -1 is the value if there is one, else −1. The last line prints the optionals raw (as Any silences the warning), so you can see the wrapper: Optional(42) and nil.

guard let: unwrap once, use everywhere below

swift
let capitals = ["Kenya": "Nairobi", "Peru": "Lima", "Vietnam": "Hanoi"]

func shout(capitalOf country: String) -> String {
    guard let city = capitals[country] else {
        return "I don't know the capital of \(country)."
    }
    // From here on, city is a plain String.
    return "The capital of \(country) is \(city.uppercased())!"
}

print(shout(capitalOf: "Peru"))
print(shout(capitalOf: "Chad"))

// Optional chaining: each ?. stops at the first nil.
let letters = capitals["Kenya"]?.count
let missing = capitals["Chad"]?.count
print(letters ?? 0, missing ?? 0)

// The shorthand form (Swift 5.7): if let city { ... } unwraps a name into itself.
let homeTown: String? = capitals["Vietnam"]
if let homeTown {
    print("Home is \(homeTown), \(homeTown.count) letters")
}
text
The capital of Peru is LIMA!
I don't know the capital of Chad.
7 0
Home is Hanoi, 5 letters

guard let is the professional's favourite. It handles the missing case first and leaves, and the unwrapped city stays in scope for the rest of the function. Compare a version with if let, where the main logic would sit one level deeper inside the braces; with three or four optionals to check, guard keeps the function flat and readable.

Optional chaining with ?. calls a method or reads a property on an optional: if the optional is nil, the whole expression stops and becomes nil; otherwise it continues. The result is always optional, even though count itself is an Int: capitals["Kenya"]?.count has type Int?. Chains can be long, as in order?.customer?.address?.city, and stop at the first nil.

Since Swift 5.7 you can write if let homeTown instead of if let homeTown = homeTown. Unwrapping an optional into a constant of the same name was so common that the language gained a shorthand for it; the same works with guard let.

switch, map and flatMap

Because Optional is an enum, everything you learned about switch applies to it:

swift
let maybe: Int? = 21
let nothing: Int? = nil

// An optional is an enum with two cases, so switch can match it.
for value in [maybe, nothing, 5] {
    switch value {
    case .some(let n) where n > 20:
        print("big:", n)
    case let n?:
        print("small:", n)
    case nil:
        print("no value")
    }
}

// map transforms the value inside, if there is one.
print(maybe.map { $0 * 2 } ?? 0, nothing.map { $0 * 2 } ?? 0)

// flatMap is for transformations that can themselves fail.
let code: String? = "404"
let parsed = code.flatMap { Int($0) }
print(parsed == 404, nothing == nil, maybe == 21)

// Chaining ?? picks the first value that exists.
let fromSettings: String? = nil
let fromEnvironment: String? = "fr"
let language = fromSettings ?? fromEnvironment ?? "en"
print(language)
text
big: 21
no value
small: 5
42 0
true true true
fr

The pattern let n? is shorthand for .some(let n). The switch needs no default: .some and nil cover everything, so the compiler knows it is exhaustive. In the array literal, the plain 5 is wrapped into an optional automatically: Swift promotes a T to a T? wherever one is expected, which is why you can pass a String to a function that takes String?.

map on an optional applies a function to the value inside, if any, and leaves nil alone. flatMap is for a function that itself returns an optional, such as Int(_:): with map you would get an Int??, an optional optional, while flatMap flattens it to Int?. Optionals can be compared with == directly; maybe == 21 is true, and nothing == nil is the idiomatic way to test for absence when you do not need the value.

Worked examplesH

Worked example: writing a function that may fail

Example— Parsing a time of day

So far we have consumed optionals that the standard library produced. Your own functions can return them too, whenever "no result" is a normal outcome. Here is a parser for times written as HH:MM on a 24-hour clock:

swift
/// Parses "HH:MM" on a 24-hour clock. Returns nil for anything else.
func parseTime(_ text: String) -> (hour: Int, minute: Int)? {
    let parts = text.split(separator: ":")
    guard parts.count == 2,
          let hour = Int(parts[0]), (0..<24).contains(hour),
          let minute = Int(parts[1]), (0..<60).contains(minute)
    else {
        return nil
    }
    return (hour, minute)
}

let entries = ["09:45", "23:59", "24:00", "7:5", "noon", "12:60", "06:30"]

for entry in entries {
    if let time = parseTime(entry) {
        print("\(entry) -> \(time.hour * 60 + time.minute) minutes after midnight")
    } else {
        print("\(entry) -> rejected")
    }
}

let valid = entries.compactMap(parseTime)
let earliest = valid.min { $0.hour * 60 + $0.minute < $1.hour * 60 + $1.minute }
if let earliest {
    print("Earliest: \(earliest.hour):\(earliest.minute)")
}
text
09:45 -> 585 minutes after midnight
23:59 -> 1439 minutes after midnight
24:00 -> rejected
7:5 -> 425 minutes after midnight
noon -> rejected
12:60 -> rejected
06:30 -> 390 minutes after midnight
Earliest: 6:30

The single guard checks five things in order, separated by commas, and the first failure jumps to else. Each let in it can use the names bound before it, so the range check on hour runs only once hour exists. When everything passes, the function returns a tuple, and Swift wraps it in an optional automatically: you write return (hour, minute), not return .some((hour, minute)).

The caller sees (hour: Int, minute: Int)? in the signature and cannot forget the failure case. Notice how the two consumers differ. The loop needs to report rejects, so it uses if let with an else. The compactMap(parseTime) line only wants the successes, so it passes the function itself as the transformation and lets the failures disappear. Then min returns an optional again, since an empty list has no minimum.

Testing with odd inputs reveals a design question: "7:5" is accepted as 7:05. Is that what you want? If the format must be exactly two digits each, add parts[0].count == 2 and parts[1].count == 2 to the guard. This is the kind of decision optionals push to the surface: every input either has an answer or does not, and you must decide which is which.

An optional says only that something failed, not why. When a caller needs the reason ("hour out of range" versus "not a number"), Swift's error handling is the better tool; you will meet it in Errors and testing. A good rule of thumb: return an optional when there is one obvious way to fail, and throw an error when there are several and the caller might react differently to each.

ExplanationH

The exclamation mark

There is one more way to unwrap, and it is the one beginners reach for first: the force unwrap, value!. It returns the wrapped value if there is one. If there is not, the program stops with Fatal error: Unexpectedly found nil while unwrapping an Optional value.

Is ! ever right? Experienced Swift developers use it sparingly, when nil would mean that the program itself is broken, not that the input was unusual. A URL that is a string literal written in the source, or a resource file bundled with the app, are typical examples: if they fail, it is a programmer's mistake that should be caught at once in testing. Even then, many teams prefer a guard let ... else { fatalError("explain what went wrong") }, which crashes just the same but leaves a message saying why.

What ! must never be is a way to make the compiler stop complaining. Every ! on data that comes from outside the program (user input, files, the network, a dictionary built at run time) is a crash waiting for the first unusual input. Linters such as SwiftLint can flag force unwraps so that each one gets a second look in code review.

You will also meet implicitly unwrapped optionals, written String!. They are optionals that unwrap themselves whenever used, crashing if nil. They exist mainly for values that are set up just after an object is created, as in some older Apple frameworks, and for code imported from Objective-C. Do not use them in new code when an ordinary optional or a non-optional will do.

History & global context

The same idea in other languages

Swift did not invent the idea of putting absence into the type. ML and Haskell had it decades earlier (Haskell calls it Maybe), and Rust, released around the same time as Swift, calls it Option. What Swift added was syntax that makes the safe path the convenient one: ?, ??, if let, guard let and optional chaining read so naturally that people use them instead of reaching for the force unwrap.

The idea has spread. Kotlin distinguishes String from String? in almost the same way; C# added nullable reference types; TypeScript's strict mode separates string from string | null; and Java and Python have Optional types and type hints that tools can check. If you learn to think in optionals here, you will recognize the pattern everywhere, and you will notice when a language lets you forget it.

Common misconceptionsH

Common misconceptions

Misconception

"nil is zero, or an empty string." nil is the absence of a value. 0 and "" are values. An Int? can be 0, and that is different from nil: "the temperature was 0 degrees" and "we have no reading" mean different things, and an optional lets you say which.

Misconception

"Optional chaining unwraps the result." a?.b is always optional, even when b is not. After a chain you still need if let, guard let or ?? to get a plain value.

Misconception

"Making everything optional is the safe choice." It is the opposite. A property that could be nil must be checked by every piece of code that uses it, forever. Make a value optional only when absence is a real, meaningful state. If a user must always have a name, the type should be String, not String?.

Misconception

"if let x = x creates a copy that I must keep in sync." The unwrapped constant is a new name for the same value, valid inside the scope. For value types it is an independent copy; changing the original afterwards does not affect it, and nothing needs to be "kept in sync" because it is a let.

Exercises

Exercises

1. Optionals

Warm-upComputational

What does this program print?

let words = ["12", "x", "3"]
let total = words.compactMap { Int($0) }.reduce(0, +)
print(total)

2. Optionals

CoreComputational

What does this program print?

let scores = ["Ana": 88, "Joon": 92]
print(scores["Ana"] ?? 0, scores["Zoe"] ?? 0, scores["Joon"].map { $0 + 1 } ?? 0)

3. Optionals

CoreComputational

What does this program print?

func describe(_ n: Int?) -> String {
    switch n {
    case nil: "none"
    case let x? where x < 0: "negative"
    case 0?: "zero"
    case let x?: "\(x)"
    }
}
print(describe(nil), describe(0), describe(-4), describe(9))

4. Optionals

CoreComputational

What does this program print?

let a: Int? = nil
let b: Int? = 0
print(a ?? b ?? 7)

5. Optionals

CoreHuman

capitals has type [String: String]. What is the type of capitals["Kenya"]?.count?

Choose one

6. Optionals

StretchComputational

code has type String?. The line let m = code.map { Int($0) } compiles. What is the type of m? Write it with question marks.

7. Optionals

CoreHuman

Your app reads a user's preferred language from a settings file at start-up; the value is a String?. What should you write?

Choose one

Further reading and resources