What’s the Difference Between Await and Async Let?
UFuk ?atalca
Senior Mobile Engineering Manager | MBA+PhD | PSM | PMP? | UI&UX | Digital Banking | Fintech | Enterprise Architecture | Digital Media | HR | Aviation | E-Commerce | Telecommunication | Insurance | Event Speaker | WWDC?
In Swift, asynchronous tasks are managed using the await and async let keywords. While these two constructs appear to serve a similar purpose, they differ fundamentally in how they work. Choosing the right one for the job can greatly impact performance and code readability.
What Is await?
await pauses the current task and waits for the asynchronous operation to complete before proceeding. It is ideal for cases where operations must be performed sequentially, with each step depending on the result of the previous one.
Example:
func fetchData() async -> Data? {
// Simulating a network request
print("Fetching data...")
await Task.sleep(2 * 1_000_000_000) // Wait for 2 seconds
print("Data fetched.")
return Data()
}
func process(_ data: Data?) async -> String {
print("Processing data...")
return "Processed data"
}
// Usage
Task {
let data = await fetchData()
let result = await process(data)
print("Result: \(result)")
}?
Output:
Fetching data...
Data fetched.
Processing data...
Result: Processed data
Here, the process function only starts after fetchData is complete, making it a sequential workflow.
What Is async let?
async let launches an asynchronous task but does not wait for it to complete immediately. It is perfect for running multiple independent tasks concurrently, improving performance.
Example:
func getNews() async -> [String] {
print("Fetching news...")
await Task.sleep(1 * 1_000_000_000) // Wait for 1 second
return ["News 1", "News 2"]
}
func getWeather() async -> [String] {
print("Fetching weather...")
await Task.sleep(2 * 1_000_000_000) // Wait for 2 seconds
return ["Sunny", "Rainy"]
}
func checkUpdate() async -> Bool {
print("Checking updates...")
await Task.sleep(1 * 1_000_000_000) // Wait for 1 second
return true
}
// Usage
Task {
async let news = getNews()
async let weather = getWeather()
async let update = checkUpdate()
let results = await (news, weather, update)
print("Results: \(results)")
}?
Output:
Fetching news...
Fetching weather...
Checking updates...
Results: (["News 1", "News 2"], ["Sunny", "Rainy"], true)
Here, tasks run concurrently, saving time compared to sequential execution.
Await vs Async Let: A Comparison
领英推荐
Graph 1: Await vs Async Let Completion Times
The following graph compares the completion times for tasks executed with await and async let. Await completes tasks sequentially, while async let runs them in parallel, reducing the overall execution time.
?
Graph 2: Sequential vs Parallel Execution Times
This graph illustrates the difference in total execution time when tasks are run sequentially versus concurrently. Parallel execution significantly reduces the total time.
?
SwiftUI Examples
Example 1: Using await
import SwiftUI
struct ContentView: View {
@State private var data: String = "Loading..."
var body: some View {
VStack {
Text(data)
.padding()
Button("Fetch Data") {
Task {
let result = await fetchDataExample()
data = result
}
}
}
}
func fetchDataExample() async -> String {
await Task.sleep(2 * 1_000_000_000) // Wait for 2 seconds
return "Data fetched successfully!"
}
}
Example 2: Using async let
import SwiftUI
struct ContentView: View {
@State private var results: (String, String) = ("Loading...", "Loading...")
var body: some View {
VStack {
Text("News: \(results.0)")
Text("Weather: \(results.1)")
.padding()
Button("Fetch Data") {
Task {
async let news = fetchNews()
async let weather = fetchWeather()
results = await (news, weather)
}
}
}
}
func fetchNews() async -> String {
await Task.sleep(2 * 1_000_000_000) // Wait for 2 seconds
return "News fetched."
}
func fetchWeather() async -> String {
await Task.sleep(1 * 1_000_000_000) // Wait for 1 second
return "Weather fetched."
}
}
Conclusion
With Swift's powerful asynchronous programming capabilities, you can improve both performance and code readability. Using the right tool in the right place will elevate the user experience in your applications.
?