0
0
iOS Swiftmobile~5 mins

Async functions in iOS Swift

Choose your learning style9 modes available
Introduction

Async functions let your app do tasks without freezing the screen. They help your app stay smooth and fast.

Loading images from the internet without stopping the app.
Fetching data from a server while letting the user keep tapping buttons.
Waiting for a file to download without making the app freeze.
Performing long calculations without blocking the user interface.
Syntax
iOS Swift
func fetchData() async -> String {
    // your code here
}

Use async after func to mark a function as asynchronous.

Call async functions with await inside another async function.

Examples
A simple async function that returns a greeting string.
iOS Swift
func greet() async -> String {
    return "Hello!"
}
Async function returning a number after some work.
iOS Swift
func fetchNumber() async -> Int {
    return 42
}
Async function that can throw errors while loading an image.
iOS Swift
func loadImage() async throws -> UIImage {
    // code to load image
}
Sample App

This SwiftUI view shows a text label. It starts with "Loading...". Then it calls an async function that waits 1 second and returns a greeting. The text updates to show the greeting without freezing the app.

iOS Swift
import SwiftUI

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

    var body: some View {
        Text(message)
            .padding()
            .task {
                message = await fetchGreeting()
            }
    }

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

Always call async functions with await inside another async context.

Use Task.sleep to simulate delays in async functions.

Async functions help keep your app responsive and smooth.

Summary

Async functions let your app do work without freezing the screen.

Mark functions with async and call them with await.

Use async to load data, images, or do long tasks smoothly.