Getting Started

Optionals

Master Swift optionals — the elegant solution to the billion-dollar null reference problem.

What are Optionals?

An optional represents a value that may or may not be present. A String? might contain a String, or it might contain nil.

This is a key safety feature of Swift. You can't accidentally use nil without explicitly handling it.

Unwrapping Optionals

  • Optional binding (if let, guard let): Safely unwrap
  • Nil coalescing (??): Provide a default value
  • Optional chaining (?): Safely access properties/methods
  • Force unwrap (!): Unwrap and crash if nil — use carefully!

guard let vs if let

Use guard let at the start of a function to exit early if a condition fails. The unwrapped value is available for the rest of the function.

Example

swift
// Optional type
var name: String? = "Alice"
var age: Int? = nil

// if let - optional binding
if let unwrappedName = name {
    print("Hello, \(unwrappedName)!")
} else {
    print("No name provided")
}

// Swift 5.7+ shorthand
if let name {
    print("Hello, \(name)!")
}

// guard let - early exit pattern
func greetUser(_ name: String?) {
    guard let name = name else {
        print("No name provided")
        return  // exit function
    }
    // name is available here as non-optional
    print("Hello, \(name)!")
}

// Nil coalescing operator ??
let displayName = name ?? "Guest"
print("Welcome, \(displayName)!")

// Optional chaining
struct Address {
    var city: String
}
struct Person {
    var name: String
    var address: Address?
}

let person = Person(name: "Bob", address: nil)
let city = person.address?.city ?? "Unknown city"
print(city)  // Unknown city

// Force unwrap (use only when certain!)
let definitelyHasValue: String? = "Hello"
let value = definitelyHasValue!  // crashes if nil!

// Optional in arrays
let values: [Int?] = [1, nil, 3, nil, 5]
let nonNil = values.compactMap { $0 }  // [1, 3, 5]
Try it yourself — SWIFT