SwiftUIMidMCQ
When should you use `task {}` vs `onAppear {}` in SwiftUI?
Test your knowledge:
Explanation & Code
Answer:
Both run code when a view appears, but task {} is purpose-built for async work.
onAppear | task | |
|---|---|---|
| Async support | ❌ No | ✅ Yes |
| Auto-cancels | ❌ No | ✅ Yes (when view disappears) |
| Retry on id change | ❌ No | ✅ With id: parameter |
Code Example:
struct ArticleView: View {
@State private var article: Article?
var body: some View {
Text(article?.title ?? "Loading...")
.task {
// automatically cancelled if view disappears
article = await ArticleService.fetch()
}
}
}
Rate your understanding: