Skip to content

Introduction to Optionals

In Swift, an Optional is a type that can hold either a value or nil (the absence of a value). This is a core safety feature that helps prevent "null pointer" errors common in other languages.

Why Optionals?

By default, standard types in Swift cannot be nil.

swift
var name: String = "Pirate"
// name = nil // ❌ Error: 'nil' cannot be assigned to type 'String'

If a value might be missing (e.g., a user's middle name or a search result), you must declare it as an optional by adding a ? to the type.

swift
var middleName: String? = nil
middleName = "William"

How Optionals Work

An optional is essentially a "box." It either contains a value (it is "wrapped") or it contains nothing (nil). To use the value inside, you must "unwrap" it.

NOTE

Type Safety: A String? is not the same as a String. You cannot use a String? directly where a String is expected without unwrapping it first.