0
0
Swiftprogramming~5 mins

Await for calling async functions in Swift

Choose your learning style9 modes available
Introduction

We use await to pause the program until an asynchronous task finishes. This helps us get results from tasks that take time, like downloading data.

When you want to download a file from the internet and wait for it to finish before moving on.
When you call a function that fetches data from a database and need the data before continuing.
When you perform a long calculation in the background and want to wait for the answer.
When you want to read a file from disk without blocking the whole app.
When you call an API that responds after some delay and you want to handle the response.
Syntax
Swift
let result = await asyncFunction()

You must call await inside an async function or context.

await tells Swift to wait for the async function to finish and give back a value.

Examples
Call fetchData() with await inside an async function to get the result.
Swift
func fetchData() async -> String {
    return "Hello" 
}

func example() async {
    let message = await fetchData()
    print(message)
}
Use Task to run async code from a non-async context and await the result.
Swift
Task {
    let number = await getNumberAsync()
    print(number)
}
Sample Program

This program waits 1 second inside fetchGreeting() and then returns a greeting. The await pauses main() until the greeting is ready.

Swift
import Foundation

func fetchGreeting() async -> String {
    // Simulate waiting for 1 second
    try? await Task.sleep(nanoseconds: 1_000_000_000)
    return "Hello, async world!"
}

@main
struct Main {
    static func main() async {
        print("Starting...")
        let greeting = await fetchGreeting()
        print(greeting)
        print("Done.")
    }
}
OutputSuccess
Important Notes

You cannot use await outside of an async function or Task context.

Using await makes your code easier to read than using callbacks.

Summary

await pauses your code until an async function finishes.

You must be inside an async function or Task to use await.

This helps write clear code that waits for slow tasks like network calls.