Implicitly unwrapped optionals can contain a value or be nil, and regular optionals can also contain a value or be nil, but there’s a subtle difference: implicitly unwrapped optionals don’t need to be unwrapped to be used. This means if you attempt to use an implicitly unwrapped optional and it’s actually nil, your code will just crash – Swift won’t make you use
if let or similar like it would with regular optionals.
In the earlier days of Swift, implicitly unwrapped optionals (IUOs) played a critical part in making our code work. However, since SwiftUI launched they are disappearing by the thousand. That’s not to say they are useless, only that they are becoming much more rare.
IUOs are useful in situations where a variable will start empty, but won’t be empty by the time you want to use it, and will stay not empty for the rest of its life. In this situation they are by definition safe to use without careful unwrapping, because they will always have a value by the time we want to use them.
The primary reason for IUOs is for use with Apple’s older UIKit user interface framework. If you wanted an image in your layout you’d need to create a property for it, but that image wouldn’t be created immediately – UIKit has a performance optimization that means the image is only created when that piece of user interface is actually shown. Apple pushes back the work of creating the image until it’s actually needed, like a lazy Swift property, but in practice it means the variable starts as nil then gets set to an image as soon as it’s needed, at which point we can start using it.
Yes, these could have been written using regular optionals, but it would have been annoying to have to unwrap them safely all the time when we know they must exist. In the SwiftUI world this whole use case goes away, so IUOs are much less important.
SPONSORED Are you tired of wasting time debugging your Swift app? Instabug’s SDK is here to help you minimize debugging time by providing you with complete device details, network logs, and reproduction steps with every bug report. All data is attached automatically, and it only takes a line of code to setup. Start your free trial now and get 3 months off exclusively for the Hacking with Swift Community.
Link copied to your pasteboard.