UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

When is it safe to force unwrap optionals?

Swift version: 5.6

Paul Hudson    @twostraws   

Some developers force unwrap optionals regularly, and some never do it, but it won’t surprise you to learn that both of those are pretty extreme and will cause you problems.

Some things are optional in Swift not because they may or may not be present, but because of historical reasons. For example, when you create a new application, your AppDelegate class has an optional UIWindow property called window. Or there’s the Bundle class, which has an optional URL property called resourceURL property that points to where your bundle’s resources are.

Both of those are optional, but if either of them fail something is seriously wrong with your application – should you really be trying to carry on running if your app is in such a corrupt state?

Think about when you try to instantiate a view controller with an identifier. Apple’s API here doesn’t throw errors, and doesn’t return an optional view controller – it just hard crashes, because there’s no sensible way for the app to continue if it’s missing a whole storyboard identifier.

You can apply that same logic to your code: if you’re trying to load a UIImage from your asset catalog, force unwrapping is a sensible thing to do because if that image is missing it means you’ve either made a serious mistake or your app is in a damaged state and forcing a crash might help limit corruption of user data.

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS 8.0

Similar solutions…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 5.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.