Optionals represent a value or the absence of one—Swift’s answer to null pointer bugs in Java and safer than unchecked null in legacy Objective-C. Type String? means optional String.
Creating and unwrapping
var nickname: String? = nil
nickname = "Ada"
if let name = nickname {
print(name)
}
let display = nickname ?? "Guest"
Compare with nullable types in Kotlin (String?) and nullable reference types in C#.
Optional chaining
let count = user?.profile?.bio?.count
Chain returns nil if any link is nil—no nested if-let pyramids.
Important interview questions and answers
- Q: Why avoid force unwrap (!)?
A: Crashes at runtime if nil—use if-let, guard, or nil-coalescing in production code. - Q: Optional vs implicitly unwrapped optional?
A:String!is still optional but auto-unwraps—legacy IBOutlet patterns; prefer regular optionals in new code.
Self-check
- What operator provides a default when optional is nil?
- What does optional chaining return if a link is nil?
Pitfall: Avoid force unwrap (!) in production—use if-let, guard, or ?? instead.
Interview prep
- Why avoid force unwrap?
Runtime crash if nil—use if-let, guard, or ??.
- Optional chaining?
Short-circuits to nil if any link is nil.