Reading — step 1 of 6
Learn
~1 min readOptionals and Errors
Swift's Optional<T> (written T?) is some(T) or nil. Swift forces you to handle both cases at compile time.
Unwrapping techniques:
let maybe: Int? = Int("42")
// 1. Optional binding (preferred)
if let n = maybe {
print(n * 2)
}
// 2. Guard — early-return if nil
func double(_ s: String) -> Int? {
guard let n = Int(s) else { return nil }
return n * 2
}
// 3. Nil-coalescing — provide a default
let n = maybe ?? 0
// 4. Optional chaining — propagate nil through the chain
let length = user?.address?.street?.count // Int? — nil at any step gives nil
// 5. Force unwrap — crashes on nil (use sparingly)
let n = maybe!
Multiple unwraps in one binding:
if let name = user?.name, let email = user?.email {
send(to: email, body: "hi \(name)")
}
map / flatMap on Optional — transform if present:
let upper = name.map { $0.uppercased() } // Optional<String>
let parsed = string.flatMap { Int($0) } // Optional<Int> (flatMap drops a level)
Swift Optionals are statically checked — you literally cannot accidentally use a nil. Compare to Java's Optional<T> which is a wrapper you can ignore.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…