The point of declaring an optional variable is to make explicit the fact that it might contain no valid value, i.e. nil
.
Force-unwrapping an optional will lead to a runtime error if the optional does contain nil
. Even if the value is tested first, it’s still
considered a bad practice to use force-unwrapping. Instead, optional binding or optional chaining should be used.
Noncompliant code example
var greeting: String?
// ...
println( \(greeting!)) // Noncompliant; could cause a runtime error
if greeting != nil {
println( \(greeting!)) // Noncompliant; better but still not great
}
Compliant solution
var greeting: String?
// ...
if let howdy = greeting {
println(howdy)
}