Optional Basics in Swift

From the Swift cheat sheet · Optionals · verified Jul 2026

Optional Basics

Declaration and unwrapping

swift
// Optional declaration
var optionalString: String? = "Hello"
var nilValue: String? = nil

// Force unwrapping (dangerous!)
let forced = optionalString!  // Crashes if nil

// Optional binding (safe)
if let unwrapped = optionalString {
    print(unwrapped)  // Safe to use
}

// Guard statement
func processValue(_ value: String?) {
    guard let unwrapped = value else {
        return  // Early exit if nil
    }
    // Use unwrapped safely here
}

// Nil coalescing
let defaultValue = optionalString ?? "Default"
💡 Prefer optional binding over force unwrapping to avoid crashes
⚡ Use guard for early returns when dealing with optionals
📌 Nil coalescing (??) provides a clean way to supply default values
🟢 Optional chaining (?.) safely accesses properties and methods
Back to the full Swift cheat sheet