How to use async and await in Swift projects

To use async await in Swift, wrap the code in a Task. If the function throws an error, use do-try-catch syntax within the Task.

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 03/22/2023 at 12:00
Last Updated on 03/22/2023 at 12:32
Two flowers representing Swift and Xcode. Beneath them sits the text "Async Await."

To use async await in Swift, wrap the code in a Task. If the function throws an error, use do-try-catch syntax within the Task.

Subscribe

Basic use

An image showing a task implementing an asynchronous function that uses await code.

To use async-await syntax without error handling, wrap the code in a task, as demonstrated in the snippet below.

This calls the function shown in the do-try-catch syntax example offered below.

Do-Try-Catch Syntax

A screenshot of an asynchronous function that uses do-try-catch. Code available below.

Do-try catch syntax allows you to handle errors that can occur as an async-await request is carried out.

To make use of do-try-catch syntax, either wrap the code in a Task (as demonstrated in the basic use example), or make your function async as shown in the code below.

If you wish for the error to be passed on with the function, use throws. An example of throws is available in Apple's Meet StoreKit 2.

Apple: Meet StoreKit 2

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe