Notice: Undefined index: understanding-swift in /var/sites/hackingwithswift.com/site/src/Controller/NewBooksReadController.php on line 89
When should you use optional try? - a free tutorial

NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

When should you use optional try?

Paul Hudson    @twostraws   

We can run throwing functions using do, try, and catch in Swift, but an alternative is to use try? to convert a throwing function call into an optional. If the function succeeds, its return value will be an optional containing whatever you would normally have received back, and if it fails the return value will be an optional set to nil.

There are advantages and disadvantages to using optional try, but it mostly centers around how important the error is to you. If you want to run a function and care only that it succeeds or fails – you don’t need to distinguish between the various reasons why it might fail – then using optional try is a great fit, because you can boil the whole thing down to “did it work?”

So, rather than writing this:

do {
    let result = try runRiskyFunction()
    print(result)
} catch {
    // it failed!
}

You can instead write this:

if let result = try? runRiskyFunction() {
    print(result)
}

If that’s what you wanted to do then you could just make runRiskyFunction() return an optional rather than throwing an error, but throwing and using optional try does give us the flexibility to change our mind later. That is, if we write a function that throws errors then at the call site we can either use try/catch or use optional try based on what we need at that point.

For what it’s worth, I use optional try a heck of a lot in my own code, because it does wonders for letting me focus on the problem at hand.

Hacking with Swift is sponsored by Essential Developer

SPONSORED From January 26th to 31st you can join a FREE crash course for iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a senior developer!

Save your spot now

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

BUY OUR BOOKS
Buy Pro Swift 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 (Vapor Edition) 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 Server-Side Swift (Kitura Edition) Buy Beyond Code

Was this page useful? Let us know!

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.