SyntaxStudy
Sign Up
Swift Optionals Fundamentals
Swift Beginner 1 min read

Optionals Fundamentals

An optional in Swift is a type that can hold either a value or nil. Declared with a ? suffix: String? is either a String or nil. This makes null pointer exceptions virtually impossible — you must explicitly handle the nil case. Optional binding (if let / guard let) safely unwraps an optional. If the optional has a value, it's bound to a constant for use in the block. If it's nil, the else branch runs. Swift 5.7 simplified optional binding: if let name (without = name) reuses the same name.
Example
// Optional declaration
var name: String? = "Alice"
var age: Int? = nil

// Force unwrap (crashes if nil - avoid)
// print(age!)  // would crash

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

// Swift 5.7+ shorthand
if let name {
    print("Name is: \(name)")
}

// guard let - early exit
func greetUser(name: String?, age: Int?) {
    guard let name else { return }
    guard let age, age >= 0 else { return }
    print("Hello \(name), you are \(age)")
}

// Nil coalescing ??
let displayName = name ?? "Anonymous"
let displayAge = age ?? 0

// Optional chaining ?.
struct Address { var city: String }
struct Person2 { var address: Address? }

let person = Person2(address: Address(city: "Tokyo"))
let city = person.address?.city   // Optional("Tokyo")
let upper = person.address?.city.uppercased()  // Optional("TOKYO")