Question 2
Optionals — guard let, if let, chaining, nil coalescing
How do you choose between guard let, if let, optional chaining, and nil coalescing for clarity and safety? When would you avoid force-unwraps?
Answer outline
Use guard let when nil means early exit, invalid state or failed preconditions, so the rest of the scope uses a non-optional binding without deep nesting.
Use if let when both branches matter and nil is not always a failure.
Optional chaining (?.) short-circuits property and method calls; combine with nil coalescing (??) to provide default values.
Avoid force unwrap (!) in production paths except in cases where you're willing to crash (e.g. IBOutlets).
Principles
??is for defaults. Prefer explicit nil checks where behavior matters.- Optional
mapandflatMapcompose without pyramidingif letchains.
guard vs if
func displayName(for user: User?) -> String {
guard let user else { return "Guest" }
return user.name
}
func subtitle(for item: Item?) -> String? {
if let item {
return item.title
}
return nil
}
Chaining + coalescing
let label = user?.profile?.displayName?.trimmingCharacters(in: .whitespaces)
let text = (label?.isEmpty == false ? label : nil) ?? "Unknown"