Swift 6 · Basics and optionals

Handle optionals

Unwrap an optional safely with if let or guard let. ?? supplies a default.

func greet(_ name: String?) -> String {
    guard let name else { return "Hello, stranger" }
    return "Hello, \(name)"
}

let length = nickname?.count ?? 0

Official Swift 6 documentation

More basics and optionals commands

All basics and optionals commands · Swift 6 cheatsheet

Was this page helpful?