Skip to content

Category: Swift

Force unwrapping is not just “not Swift-like.” It’s wrong.

Swift comes with a number of features that help developers write correct bug-free programs: optionals, safe casting, and built-in error handling. But for every one of these, there is an escape hatch: !, the force unwrapping operator.

You may know another developer or team member who plays a little fast and loose with force unwrapping. Or you don’t feel like doing the additional boilerplate to unwrap an optional, so you do it when “nobody’s looking.”

You may not have a good argument for why safe unwrapping is good and force unwrapping is bad, other than that the Swift documentation says so, or “that’s how it’s done.”

The reason behind safe unwrapping comes from a long history of languages that didn’t provide strong safeties such as these. This often resulted in trying to interpret random memory locations as objects, resulting in crashes at best, hard to debug app behavior at worst. Not using all of Swift’s safety mechanisms at your disposal is not just not Swift-like, it is bad programming.