Do you find your Swift code riddled with
I’m becoming more and more uncomfortable with seeing
! throughout my Swift code. It’s just a matter of time before it’s going to bite me.
Often, I do it because it’s the “easy thing” to do at the time. But it’s dangerous.
Swift optionals are trying to help us. They force us to deal with the possibility of something not having a value.
By force unwrapping an optional with the
! operator, we’re declaring, “This will never be without a value”. Really? Never? Are you sure? Only a Sith deals in those kinds of absolutes.
When a function returns an optional, or a property is declared as optional, we are, at the very least, meant to assume that there is a possibility of
nil lying underneath.
Therefore, I’m considering it a sort of “code smell” when I see it in my own code. It’s not too much to throw an
if let or a
guard let in there to handle the possibility of
Two exceptions to the code smell rule:
1 – IBOutlet and IBAction
IBOutlets and IBActions are force-unwrapped, but that’s because they get injected when the Storyboard is loaded at run-time. It’s assumed that these are connected and will be supplied when the scene is loaded. If they get unwired somehow, we want an instant crash so we know to go back to the Storyboard and re-wire things to the view controller.
2 – Required properties to be set in prepareForSegue
Along those same lines, I consider properties that must be set when navigating to a new view controller to be in the same category as an IBOutlet or an IBAction. I want to know right away if I forget to set those in
prepareForSegue in the parent view controller. So I’ll often force unwrap the optional in the declaration so that there’s an as-immediate-as-possible crash if it’s not set.
Hopefully when you’re working with optionals from here on, you’ll take a second sniff when you see the