Forced Unwrapped
ID |
swift.forced_unwrapped |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Swift |
Tags |
optional, reliability |
Description
Reports postfix ! on an Optional value (force unwrap). If the Optional
is nil at runtime, the program crashes with "unexpectedly found nil
while unwrapping an Optional value".
let p = findPlayer(id)
p!.winCoins(100) // FLAW
findPlayer(id)!.coins // FLAW (chained)
guard let p = findPlayer(id) else { return }
p.winCoins(100) // OK
findPlayer(id)?.coins ?? 0 // OK
Rationale
Force-unwrap defeats Swift’s null-safety guarantees. The Optional type exists precisely so the compiler can force the developer to handle the nil case. Force-unwrap punts that handling to runtime — and the failure mode is an unrecoverable crash.
Acceptable narrow exceptions:
-
@IBOutletproperties (lifecycle binds before first access). -
Test code where the Optional is provably non-nil.
Remediation
// Optional binding (if let / guard let)
if let p = findPlayer(id) {
p.winCoins(100)
}
guard let p = findPlayer(id) else { return }
p.winCoins(100)
// Optional chaining + nil-coalescing
let coins = findPlayer(id)?.coins ?? 0
// Optional chaining for fire-and-forget
findPlayer(id)?.winCoins(100)