How can I deal with asynchronous tasks in Swift?

ByungwookAn
3 min readOct 6, 2023

--

image source : https://developer.apple.com/xcode/swiftui/

Intro

In my previous article, I talked about Synchronous / Asynchronous and DispatchQueue. In this article, I emphasized the importance of Synchronous for efficient programming. Today, I’ll Introduce async/await, another way to operate synchronously. It is a convenient and readable way to operate synchronously.

If you want to see my previous article about DispatchQueue, check this link below.

The basic concept of async/await

Async/await are released in WWDC 2021, and available in Swift 5.5 and later. Before 2021, There was a lot of asynchronous (or “async”) programming using closures and completion handlers. But These are hard to use and complicated. Async/await makes asynchronous programming a lot more natural and less error prone.

async is used to define asynchronous functions or blocks of code. An asynchronous function is one that can perform work in the background without blocking the main thread.

await is a command that synchronizes the execution of an asynchronous function. That is, it waits until the execution of the corresponding asynchronous function is finished in the current thread. await can only be written within asynchronous functions marked as async because it causes blocking.

you can check the official document & video in this link.

How to use & Explanation

Here’s the sample code of using async & await.

import SwiftUI

struct ContentView: View {
@State private var data: String = "Loading..."

var body: some View {
Text(data)
.onAppear {
Task {
do {
let fetchedData = try await fetchData()
data = fetchedData
} catch {
data = "Error: \(error.localizedDescription)"
}
}
}
}

func fetchData() async throws -> String {

await Task.sleep(3 * 1_000_000_000) // 3sec

return "Data fetched successfully!"
}
}

First, When ContentView starts, “Loading” appears first. When the view appears, it starts an asynchronous task using the Task construct.

Inside the Task, we call the fetchData() using await. The await keyword allows the task to pause until the data is available.

After 3 seconds, “Data Fetched successfully!” appears.

Point to note

I’m confused between async/await and DispatchQueue.main. async/await is distinct from DispatchQueue.main.async and DispatchQueue.main.sync. Both sets of concepts deal with asynchronous and synchronous execution in Swift, but they operate in different ways. Async/await is a higher-level language feature for simplifying asynchronous code, whereas DispatchQueue.main.async and DispatchQueue.main.sync are mechanisms for managing concurrency and updating the UI on the main thread in multithreaded environments.

Conclusion

async & await allows you to write asynchronous code more easily and safely. So if you use async & await the right way, It will be a great tool to make the app more efficient.

--

--