0
0
iOS Swiftmobile~5 mins

Why async/await simplifies concurrent code in iOS Swift

Choose your learning style9 modes available
Introduction

Async/await makes writing code that does many things at once easier to read and understand. It helps your app stay fast and smooth without complicated code.

When your app needs to load data from the internet without freezing the screen.
When you want to run tasks like saving files or fetching images in the background.
When you need to wait for a slow task to finish before moving on, but don't want the app to stop working.
When you want to write clear and simple code that handles multiple tasks at the same time.
Syntax
iOS Swift
func fetchData() async throws -> String {
    let data = try await downloadFromInternet()
    return data
}

Task {
    do {
        let result = try await fetchData()
        print(result)
    } catch {
        print("Error: \(error)")
    }
}

async marks a function that can pause and wait for work to finish.

await tells the code to wait for a task without blocking the whole app.

Examples
This function waits for an image to download before returning it.
iOS Swift
func loadImage() async -> UIImage {
    let image = await fetchImageFromServer()
    return image
}
Run async code inside a Task to start it from a normal context.
iOS Swift
Task {
    let data = try await fetchData()
    print(data)
}
Run two tasks at the same time and wait for both to finish.
iOS Swift
func process() async {
    async let first = fetchFirstData()
    async let second = fetchSecondData()
    let results = await (first, second)
    print(results)
}
Sample App

This SwiftUI view shows a loading message, waits 2 seconds asynchronously, then updates the text. The UI stays responsive during the wait.

iOS Swift
import SwiftUI

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

    func fetchMessage() async -> String {
        try? await Task.sleep(nanoseconds: 2_000_000_000) // wait 2 seconds
        return "Hello from async/await!"
    }

    var body: some View {
        Text(message)
            .padding()
            .task {
                message = await fetchMessage()
            }
    }
}
OutputSuccess
Important Notes

Async/await helps avoid deeply nested callbacks, making code easier to read.

Use Task or .task modifier to start async code in SwiftUI.

Remember to handle errors with try and catch when using async functions that can throw.

Summary

Async/await lets your app do many things at once without freezing.

It makes code look simple and easy to follow.

Use it to keep your app fast and user-friendly.