SyntaxStudy
Sign Up
Swift Optional Chaining and Map
Swift Beginner 1 min read

Optional Chaining and Map

Optional chaining propagates nil through a chain of property accesses and method calls. The result is always an optional. This replaces nested nil checks with clean, readable code. Optionals are monads — they support map and flatMap. Optional.map applies a transform if the value is present. Optional.flatMap applies a transform that itself returns an optional, preventing double-wrapping. The compactMap function on arrays applies a transform returning Optional and automatically drops nil results.
Example
struct Order {
    var id: Int
    var customer: Customer?
}

struct Customer {
    var name: String
    var address: Address?
    func loyaltyPoints() -> Int? { nil } // might not be enrolled
}

struct Address {
    var city: String
    var country: String
}

let order = Order(id: 1, customer: Customer(name: "Alice", address: Address(city: "London", country: "UK")))

// Optional chaining
let city = order.customer?.address?.city          // Optional("London")
let points = order.customer?.loyaltyPoints()      // Optional(Optional(nil)) without flatMap

// Optional.map
let upperCity = city.map { $0.uppercased() }      // Optional("LONDON")

// Optional.flatMap - flattens Optional<Optional<T>>
let safePoints = order.customer.flatMap { $0.loyaltyPoints() }  // nil

// compactMap on array
let strings = ["1", "abc", "3", "xyz", "5"]
let numbers = strings.compactMap(Int.init)        // [1, 3, 5]

// Chaining with subscript
let scores: [String: [Int]] = ["Alice": [90, 85, 92]]
let firstScore = scores["Alice"]?.first           // Optional(90)