Skip to content
Swift

Optionals

Use optional binding, nil-coalescing, chaining, and guard for safe unwrapping.

By EZ4Code Team
optionalbinding

Code

import Foundation

// Optional declaration
let name: String? = "Alice"
let missing: String? = nil

// Optional binding
if let actual = name {
    print("Hello, \(actual)")
}

// Multiple binding
if let first = name, let second = missing {
    print("\(first) and \(second)")
} else {
    print("at least one is nil")
}

// Nil-coalescing operator
let value = missing ?? "default"
print(value)

// Optional chaining
struct User { var address: Address? }
struct Address { var city: String }
let user = User(address: Address(city: "Paris"))
print(user.address?.city ?? "unknown")

// Guard statement for early exit
func greet(_ who: String?) {
    guard let who else { print("no name"); return }
    print("Hi \(who)")
}
greet(name)

Explanation

Optionals wrap a value or nil, forcing the compiler to track the absence of a value explicitly. if let and guard let safely unwrap and branch, while ?? supplies a default. Optional chaining short-circuits the whole expression to nil as soon as any link is nil.

More Swift Snippets