(tl;dr: force unwrapping in Swift with ! is bad)
At our last iOS Developer meetup in Limerick, my Worst Case Scenario podcast co-host Dave Sims gave an excellent talk on Optionals in Swift. I’m hoping that Dave will put the content online some day as he really managed to provide a simple yet powerful overview of what Optionals are. He also ended up being invited to give his talk to the CocoaHeads meetup in Indianapolis via Skype – check out Worst Case Scenario Episode 36 for the details about how that came about.
Dave mentioned in his talk that force unwrapping Optionals is generally a bad idea. Xcode doesn’t help the matter though by actually encouraging programmers to force-unwrap optionals:
This is terrible advice for programmers new (or not-so-new…) to Swift. Force unwrapping a nil optional will cause a runtime crash. The whole point of optionals is you make a whole class of bug, where a nil creeps in and causes havoc down the line, impossible. Force-unwrapping throws all of this away with the dubious upside of saving a line or two (and shutting up the compiler). You can argue that the Apple documentation is pretty clear about force unwrapping being a bad idea, but I feel the tools should be encouraging best behaviour. Dave mentioned three common unwrapping techniques:
if let
guard let
- The
?? nil
coalescing operator to provide a default value
Dave also mentioned Chris Lattner’s recent appearance on Accidental Tech Podcast where Swift’s creator talked about the purpose of the guard statement was to allow early exit (Overcast link that jumps directly to that segment), a style which he is personally in favour of. I also like this style – it reduces the indentation for the main bit of the code. You just have to remember to actually exit the block, either by asserting or returning a default value.