import SwiftUI
struct AsyncAwaitDemo: View {
@State private var resultText = ""
@State private var isLoading = false
var body: some View {
VStack(spacing: 20) {
Text("Async/Await Demo")
.font(.title)
Button("Start Tasks") {
Task {
await runTasksSequentially()
}
}
.padding()
.disabled(isLoading)
if isLoading {
ProgressView()
}
Text("Result: \n" + resultText)
.padding()
.multilineTextAlignment(.center)
Spacer()
}
.padding()
}
func taskOne() async -> String {
try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
return "Task One Done"
}
func taskTwo() async -> String {
try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
return "Task Two Done"
}
func runTasksSequentially() async {
isLoading = true
let firstResult = await taskOne()
let secondResult = await taskTwo()
resultText = "\(firstResult) and \(secondResult)"
isLoading = false
}
}
struct AsyncAwaitDemo_Previews: PreviewProvider {
static var previews: some View {
AsyncAwaitDemo()
}
}This example uses Swift's async/await to run two tasks one after another. Each task waits 2 seconds and returns a string. The runTasksSequentially function awaits each task in order, making the code easy to read like normal sequential code.
The button triggers the async function using Task { await ... }. While tasks run, a loading spinner shows and the button disables to prevent multiple taps.
This approach is simpler and cleaner than nested callbacks or completion handlers. It reads like normal code but runs asynchronously without blocking the UI.