Unwrap an optional safely
Handle a missing value without force-unwrapping.
let name: String? = "Sam"
if let name { print("Hello, \(name)") }
let missing: String? = nil
print(missing ?? "Anonymous")How it works
An optional stores a value or nil. Optional binding makes the unwrapped value available inside the conditional block. Nil coalescing supplies a fallback.
EXPECTED OUTPUT
Hello, Sam Anonymous
Keep in mind
Avoid force unwrapping unless an invariant guarantees the value exists.