Optionals and Error Handling

Article · 2:00

nil without null-pointer crashes, and the do-try-catch that makes failure part of a function's type.

An optional is Swift's answer to the billion-dollar mistake. A String always holds a string. A String? holds either a string or nil, and the compiler will not let you use it as a string until you have said what should happen when it is nil. The absence of a value becomes a case you have to handle rather than a crash you discover in production.

There are four ways to get at the value, and three of them are good. if let unwraps into a new constant for the length of a block. guard let unwraps and keeps the value in the surrounding scope, exiting early if it is nil - this is the one to reach for at the top of a function, because it keeps the happy path unindented. ?? supplies a default. And ! force-unwraps, which crashes if the value is nil; write it only where nil would mean the program is already broken.

Errors are separate from optionals and answer a different question: not "is there a value" but "why is there not one". A function that can fail is marked throws, its callers must write try, and the failure is handled in a do ... catch. Because throws is part of the function's type, you cannot forget to handle it - the compiler knows.

// Int("42") can fail, so it returns Int? rather than Int.
let typed = "42"
let parsed = Int(typed)          // Optional(42)

// 1. if let - the value exists only inside the block.
if let number = parsed {
    print("got \(number)")
}

// 2. guard let - unwrap, keep it, leave early if nil. Preferred at the top.
func describe(_ raw: String) -> String {
    guard let value = Int(raw) else {
        return "not a number"
    }
    return "twice is \(value * 2)"   // value is a plain Int from here on
}

// 3. ?? - a default.
let count = Int("oops") ?? 0

// Errors say WHY, where an optional only says whether.
enum LoadError: Error {
    case notFound
    case badFormat(line: Int)
}

func load(_ name: String) throws -> String {
    guard name == "config" else { throw LoadError.notFound }
    return "ok"
}

do {
    let text = try load("missing")
    print(text)
} catch LoadError.notFound {
    print("no such file")
} catch {
    print("something else: \(error)")
}

print(describe("21"), count)