Optionals
This is the idea that makes Swift feel distinctly Swift. Any value that might legitimately be absent — a dictionary lookup that might not find a key, a number parsed from text that might not be a valid number — has type Optional<T>, written T?, and the compiler won't let you use it as if it were guaranteed to exist.
Declaring an optional
var nickname: String? = "Ace" var middleName: String? = nil print(nickname as Any) print(middleName as Any)
Optional("Ace")
nilThe ? after String means "a String, or nothing at all." Printing an optional directly shows it still wrapped in Optional(...) — you haven't proven to the compiler yet that a value is actually there.
Safely unwrapping with if let
let nickname: String? = "Ace" if let unwrapped = nickname { print("Nickname: \(unwrapped)") } else { print("No nickname set") }
Nickname: Ace
if let unwrapped = nickname only enters the block when nickname actually holds a value, and inside that block unwrapped is a plain, non-optional String — the compiler has proven it's safe to use directly.
guard let: unwrap or exit early
func greet(_ nickname: String?) { guard let name = nickname else { print("No name provided") return } print("Hello, \(name)!") } greet("Priya") greet(nil)
Hello, Priya! No name provided
guard let reads as "make sure this exists, or bail out right here" — unlike if let, the unwrapped value stays available for the rest of the function after the guard, not just inside a nested block.
The nil-coalescing operator
let nickname: String? = nil let displayName = nickname ?? "Anonymous" print(displayName)
Anonymous
nickname! tells the compiler "trust me, this definitely has a value" and skips all the safety checks above — but if you're wrong and it's actually nil, your program crashes instantly at runtime with no chance to recover. if let, guard let, and ?? exist specifically so you almost never need !. Treat every ! you write as a claim you'd better be able to back up.