Skip to content
Swift

Optionals

Use optional binding, nil-coalescing, chaining, and guard for safe unwrapping.

#optional#binding

Code

swift
import Foundation

// Optional declaration
let name: String? = "Alice"
let missing: String? = nil

// Optional binding
if let actual = name {
    print("Hello, \(actual)")
}

// Multiple binding
if let first = name, let second = missing {
    print("\(first) and \(second)")
} else {
    print("at least one is nil")
}

// Nil-coalescing operator
let value = missing ?? "default"
print(value)

// Optional chaining
struct User { var address: Address? }
struct Address { var city: String }
let user = User(address: Address(city: "Paris"))
print(user.address?.city ?? "unknown")

// Guard statement for early exit
func greet(_ who: String?) {
    guard let who else { print("no name"); return }
    print("Hi \(who)")
}
greet(name)