Back to Swift Reference Ask BeeAI
📱 SwiftUIIntermediateiOS 15+
.task & Loading Data
Start async work when a view appears — automatically cancelled when it disappears.
.task runs an async closure tied to the view's lifetime. It is the right place to load data, replacing onAppear + Task { }.
Use .task(id:) to restart the work whenever a value changes, such as a search query.
task-modifier.swift
1struct Post: Decodable, Identifiable { let id: Int; let title: String }
2
3struct PostsView: View {
4 @State private var posts: [Post] = []
5 @State private var errorMessage: String?
6
7 var body: some View {
8 List(posts) { Text($0.title) }
9 .overlay { if let errorMessage { Text(errorMessage) } }
10 .task { await load() }
11 }
12
13 private func load() async {
14 do {
15 let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
16 let (data, _) = try await URLSession.shared.data(from: url)
17 posts = try JSONDecoder().decode([Post].self, from: data)
18 } catch {
19 errorMessage = error.localizedDescription
20 }
21 }
22}Common pitfalls
- Always handle errors and show a state to the user — never leave an infinite spinner.
Still unclear? Ask BeeAI about .task & Loading Data.
Get a tailored explanation, or paste your own code for a Swift 6 review. Free members get daily questions — Pro is unlimited.
Related topics
Become a Founding Pro member: unlimited BeeAI, upcoming Swift paths and every new reference entry first.
See Pro Plans