Thursday, June 29, 2017

Banning Force Unwrapping Swift Optionals

Alexandre Colucci:

Download a random Sample Code from Apple Developer website and look if and how force unwrapping is used.


Xcode’s Fix-it feature proposes to insert the explicit unwrap operator… even when it doesn’t make sense[…]


There are multiple solutions that are cleaner and safer than using an explicit unwrap. I also generally find the code more readable. Below are several examples.


Similarly to force unwrapping an optional, I see a lot of code dangerously using implicit unwrapped optionals. This kind of optionals should also be avoided… except in one case where it is extremely useful: When declaring an IBOutlet, you should use an implicit unwrapped optional because once the method viewDidLoad is called, the IBOutlet will be initialized.

Another case where IUOs are unfortunately needed is in test code, because the variables aren’t initialized until set setUp() method.

Comments RSS · Twitter

Leave a Comment