swift · note · optionals
Force Unwrapping in Swift: Red Lines
Context
Force unwrapping is not just a syntax choice. It is a promise that the value will exist, and that promise should be rare and obvious.
The snippet
let bundleName = Bundle.main.infoDictionary!["CFBundleName"] as? String ?? "App"
Why this works
The example shows the boundary clearly: the fallback is trivial, and the app can keep moving. But the force unwrap itself should be treated as a warning sign, not a habit.
Use it when:
- a value is guaranteed by the platform or test setup
- the crash would reveal a truly impossible state
- the code is tiny and well-contained
Avoid it when:
- the value can actually be missing
- the code path is user-facing and recoverable
- you are using
!because the optional handling feels annoying
Takeaway: Force unwraps belong at red lines, not in normal app logic.