0
0
Swiftprogramming~5 mins

Task for launching concurrent work in Swift

Choose your learning style9 modes available
Introduction

Tasks let you run work at the same time without waiting. This helps your app stay fast and smooth.

When you want to download images while still letting the user tap buttons.
When you need to fetch data from the internet without freezing the screen.
When you want to do some heavy math in the background while showing results later.
When you want to start multiple jobs at once and wait for all to finish.
When you want to update UI only after some background work is done.
Syntax
Swift
Task {
    // code to run concurrently
}

The code inside Task { } runs asynchronously.

You can use await inside the task to wait for other async work.

Examples
This starts a task that prints a message without blocking the main thread.
Swift
Task {
    print("Hello from a task!")
}
This task waits for fetchData() to finish before printing.
Swift
Task {
    let data = await fetchData()
    print("Data received: \(data)")
}
This task runs a loop with pauses, showing how to do timed work concurrently.
Swift
Task {
    for i in 1...3 {
        print("Task running step \(i)")
        try? await Task.sleep(nanoseconds: 500_000_000) // 0.5 seconds
    }
}
Sample Program

This program starts a task that waits 1 second, then prints a message. The main run loop keeps running so we can see the output.

Swift
import Foundation

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

Task {
    let message = await fetchData()
    print(message)
}

// Keep the program running to see the task output
RunLoop.main.run(until: Date().addingTimeInterval(2))
OutputSuccess
Important Notes

Tasks run concurrently but do not block your main thread.

Use await inside tasks to pause until async work finishes.

Remember to keep your program running if you want to see task output in playgrounds or scripts.

Summary

Use Task { } to start work that runs at the same time as other code.

Inside a task, you can use await to wait for async functions.

Tasks help keep your app responsive by doing work in the background.