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

How to call async throwing functions

Paul Hudson    @twostraws   

Updated for Xcode 15

Just like their synchronous counterparts, Swift’s async functions can be throwing or non-throwing depending on how you want them to behave. However, there is a twist: although we mark the function as being async throws, we call the function using try await – the keyword order is flipped.

To demonstrate this in action, here’s a fetchFavorites() method that attempts to download some JSON from my server, decode it into an array of integers, and return the result:

func fetchFavorites() async throws -> [Int] {
    let url = URL(string: "https://hws.dev/user-favorites.json")!
    let (data, _) = try await URLSession.shared.data(from: url)
    return try JSONDecoder().decode([Int].self, from: data)
}

if let favorites = try? await fetchFavorites() {
    print("Fetched \(favorites.count) favorites.")
} else {
    print("Failed to fetch favorites.")
}

Download this as an Xcode project

Both fetching data and decoding it are throwing functions, so we need to use try in both those places. Those errors aren’t being handled in the function, so we need to mark fetchFavorites() as also being throwing so Swift can let any errors bubble up to whatever called it.

Notice that the function is marked async throws but the function calls are marked try await – like I said, the keyword order gets reversed. So, it’s “asynchronous, throwing” in the function definition, but “throwing, asynchronous” at the call site. Think of it as unwinding a stack.

Not only does try await read more easily than await try, but it’s also more reflective of what’s actually happening when our code executes: we’re waiting for some work to complete, and when it does complete we’ll check whether it ended up throwing an error or not.

Of course, the other possibility is that they could have try await at the call site and throws async on the function definition, and here’s what the Swift team says about that:

“This order restriction is arbitrary, but it's not harmful, and it eliminates the potential for stylistic debates.”

Personally, if I saw throws async I’d be more likely to write it as “this thing throws an async error” or similar, but as the quote above says ultimately the order is just arbitrary.

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Similar solutions…

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: 4.3/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.