Before async/await, a network call took a completion handler, and three calls in sequence produced the pyramid of closures everyone recognises. await flattens it. The line let data = try await fetch() suspends the function until the result arrives and then continues on the next line, with the error handling in an ordinary do ... catch. The thread is not blocked while it waits - that is the whole point, and it is the same idea as a Kotlin coroutine.
async functions can only be called from other async contexts. The bridge from synchronous code is Task { }, and in SwiftUI the .task { } modifier is better still, because it starts when the view appears and cancels automatically when the view goes away - which is most of the lifecycle management you would otherwise write by hand.
When two pieces of work do not depend on each other, run them at the same time with async let, then await both. Two sequential 300 ms calls take 600 ms; the same two concurrent take 300 ms.
An actor is a type that protects its own state: only one task touches its interior at a time, so a data race is not possible. Mark things that must run on the main thread - anything touching the interface - with @MainActor.
import SwiftUI
@MainActor
@Observable
final class FeedModel {
var articles: [Article] = []
var isLoading = false
var failure: String?
func load() async {
isLoading = true
defer { isLoading = false }
do {
// Independent work, started together rather than one after another.
async let latest = fetchArticles()
async let featured = fetchArticles()
articles = try await latest + featured
failure = nil
} catch is CancellationError {
// The view went away. Not a failure worth showing.
} catch {
failure = error.localizedDescription
}
}
}
// An actor serialises access to its own state - no locks to remember.
actor RequestCounter {
private var count = 0
func record() -> Int { count += 1; return count }
}
struct FeedScreen: View {
@State private var model = FeedModel()
var body: some View {
List(model.articles) { article in
Text(article.title)
}
.overlay { if model.isLoading { ProgressView() } }
// .task starts on appear and CANCELS when the view disappears.
.task { await model.load() }
.refreshable { await model.load() }
}
}