0
0
Swiftprogramming~5 mins

Async functions declaration in Swift

Choose your learning style9 modes available
Introduction

Async functions let your program wait for tasks that take time, like downloading data, without stopping everything else.

When you want to fetch data from the internet without freezing the app.
When reading or writing files that might take a moment.
When calling a slow service and you want the app to stay responsive.
When you want to run tasks in the background and get results later.
Syntax
Swift
func functionName() async -> ReturnType {
    // code that can wait
}

The async keyword tells Swift this function can pause and wait.

You call async functions using await to wait for their result.

Examples
A simple async function that returns a string.
Swift
func fetchData() async -> String {
    return "Data received"
}
An async function that can also throw errors.
Swift
func loadImage() async throws -> UIImage {
    // code that might fail
}
An async function that does work but returns nothing.
Swift
func process() async {
    // async work without returning a value
}
Sample Program

This program defines an async function that waits 1 second and then returns a message. The main async function calls it using await and prints the result.

Swift
import Foundation

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

@main
struct Main {
    static func main() async {
        let message = await fetchMessage()
        print(message)
    }
}
OutputSuccess
Important Notes

You must mark the caller function as async to use await.

Async functions help keep apps smooth by not blocking the main thread.

Summary

Use async to declare functions that can pause and wait.

Call async functions with await inside other async functions.

This helps your app stay responsive during slow tasks.