Swift Coding Feature: Asynchronous Programming with Async/Await

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
April 15, 2023

Swift Coding Feature: Asynchronous Programming with Async/Await

Asynchronous programming in Swift is used to avoid blocking the main thread of your application. With Apple's recent release of iOS 15, they introduced a new way to write asynchronous code in Swift with the async/await syntax. This syntax enables developers to write asynchronous code more clearly and concisely.

How to Use Async/Await in Swift

Async/await can be used in Swift to run certain functions that may take a long time to execute such as fetching data from an API, decoding JSON, or performing network calls.

  1. To use async/await functions in Swift, the function must be marked with the async keyword. For example:
async func fetchData() -> [String] {
    let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
    let (data, _) = try await URLSession.shared.data(from: url)
    let response = try! JSONDecoder().decode([Post].self, from: data)
    return response.map { $0.title }
}
  1. Inside the async function, we use await to pause the function until the asynchronous task is complete.
  2. The result of an async function will always be a Task object. To get the result of a Task, we use await.
  3. The above code snippet demonstrates how to fetch data from an API and decode it, returning an array of post titles.

It is important to note that, by default, async functions run on the background thread to prevent blocking the main thread, but you can specify the dispatch queue to run it by using await(..., on: ) function.

Conclusion

The async/await syntax is a convenient and simple way to write asynchronous code in Swift. With the introduction of iOS 15, it is now easier than ever to write asynchronous code efficiently and effectively.