Skip to content
The App Code
Concept

Optionals in Swift

A type-level way to represent the presence or absence of a value, forcing you to handle nil explicitly.

Also known as: Swift nil safety, Optional type

beginner

An Optional<T> (written T?) either holds a value or is nil. Swift makes the possibility of absence part of the type, so you must unwrap before use.

What it is

Swift models "a value might be missing" with the Optional type, written T?. A non-optional Int can never be nil; only an Int? can. This pushes null-handling to compile time: you cannot accidentally use a missing value, because the compiler won't let you treat an Int? as an Int until you unwrap it.

Safe unwrapping uses if let/guard let to bind the value when present, the nil-coalescing operator ?? to supply a default, and optional chaining (user?.name) to short-circuit to nil down a chain. This is Swift's answer to the null-pointer errors common in other languages.

Worked example

var name: String? = nil

// Safe unwrap with a default
print(name ?? "Anonymous") // Anonymous

name = "Ada"
if let unwrapped = name {
    print("Hello, \(unwrapped)") // Hello, Ada
}

// Optional chaining
let length = name?.count // Optional(3)

Failure mode — when it misleads

The force-unwrap operator ! (e.g. name!) bypasses the safety and crashes at runtime if the value is nil — a leading cause of avoidable crashes. Reserve ! for cases that are logically impossible to be nil, and prefer guard let with an early return everywhere else.

Sources & further reading