Quick Answer
Handle nil optionals safely.
Understanding the Issue
Swift requires optionals to be properly initialized before use, preventing null reference exceptions.
The Problem
This code demonstrates the issue:
Swift
Error
var name: String?
print(name!) // Crash if nil
The Solution
Here's the corrected code:
Swift
Fixed
// Solution 1: Optional binding
if let unwrappedName = name {
print(unwrappedName)
}
// Solution 2: Nil coalescing
print(name ?? "default")
// Solution 3: Guard statement
guard let safeName = name else {
print("Name is nil")
return
}
print(safeName)
// Solution 4: Initialize properly
var name: String? = "Initial Value"
Key Takeaways
Always unwrap optionals safely using proper Swift idioms.