Optionals & Error Handling

June 02, 2026 1 min read

An optional may hold a value or be nil. Swift forces you to unwrap it, preventing crashes from missing data.

Optionals

var email: String? = nil
// safe unwrap
if let e = email { print(e) }
// default with ??
let shown = email ?? "no email"
// guard for early exit
func send(to email: String?) {
    guard let e = email else { return }
    // use e safely
}

Error handling

enum LoginError: Error { case invalid }
func login(_ ok: Bool) throws {
    if !ok { throw LoginError.invalid }
}
do {
    try login(false)
} catch {
    print("Failed: \(error)")
}
Common mistake: Avoid force-unwrapping with ! unless you are 100% sure — it crashes the app if the value is nil.

Summary

Optionals + safe unwrapping (if let, guard, ??) and do/try/catch keep your app crash-free when data or operations may fail.