Experimenting with Swift async and await pattern using Xcode

Rizwan Ahmed
2 min readDec 27, 2020
Experimenting with Swift async and await pattern using Xcode

You all might know that async/await is accepted and is available in the main snapshots! Let’s get our hands dirty by trying out some basic example of async/await in Swift.

Prerequisites

  1. Xcode 12.3
  2. Latest Swift Toolchain (You can download it from here)

Installing the Swift Toolchain

Download the Swift Toolchain, and install the .pkg file. After installing the Swift toolchain, open Xcode and go to Preferences -> Components and select “Swift Development Snapshot”

Swift Development Toolchain

Next, go to your Project’s build settings and add the following Swift flags “-Xfrontend -enable-experimental-concurrency ”

Swift Compiler Flags

Using completion handlers to handle asynchronous tasks

We usually use completion handlers for handling asynchronous tasks. For example,

The above code is OK, but there are too many things going on. It is error-prone, and the code starts falling apart when nesting of multiple completion handlers is required, which eventually leads to the pyramid of doom. Let’s find out how to re-write the above code using the new async await approach.

Replacing completion handlers with async/await

When you write async/await code, the boilerplate code is reduced, and it allows us to focus on improving the performance of the concurrent code. Let’s see how to write it.

Continue reading the rest of the article here.

--

--