How to create and run a task
How to create and run a task êŽë š
Updated for Xcode 15
Swiftâs Task
struct lets us start running some work immediately, and optionally wait for the result to be returned. And it is optional: sometimes you donât care about the result of the task, or sometimes the task automatically updates some external value when it completes, so you can just use them as âfire and forgetâ operations if you need to. This makes them a great way to run async code from a synchronous function.
First, letâs look at an example where we create two tasks back to back, then wait for them both to complete. This will fetch data from two different URLs, decode them into two different structs, then print a summary of the results, all to simulate a user starting up a game â what are the latest news updates, and what are the current highest scores?
Hereâs how that looks:
struct NewsItem: Decodable {
let id: Int
let title: String
let url: URL
}
struct HighScore: Decodable {
let name: String
let score: Int
}
func fetchUpdates() async {
let newsTask = Task { () -> [NewsItem] in
let url = URL(string: "https://hws.dev/headlines.json")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode([NewsItem].self, from: data)
}
let highScoreTask = Task { () -> [HighScore] in
let url = URL(string: "https://hws.dev/scores.json")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode([HighScore].self, from: data)
}
do {
let news = try await newsTask.value
let highScores = try await highScoreTask.value
print("Latest news loaded with \(news.count) items.")
if let topScore = highScores.first {
print("\(topScore.name) has the highest score with \(topScore.score), out of \(highScores.count) total results.")
}
} catch {
print("There was an error loading user data.")
}
}
await fetchUpdates()
Letâs unpick the key parts:
- Creating and running a task is done by using its initializer, passing in the work you want to do.
- Tasks donât always need to return a value, but when they do chances are youâll need to declare exactly what as you create the task â Iâve said
() -> [NewsItem] in
, for example. - As soon as you create the task it will start running â thereâs no
start()
method or similar. - The entire task is run concurrently with your other code, which means it might be able to run in parallel too. In our case, that means fetching and decoding the data happens inside the task, which keeps our main
fetchUpdates()
function free. - If you want to read the return value of a task, you need to access its
value
property usingawait
. In our case our task could also throw errors because weâre accessing the network, so we need to usetry
as well. - Once youâve copied out the value from your task you can use that normally without needing
await
ortry
again, although subsequent accesses to the task itself â e.g.newsTask.value
â will needtry await
because Swift canât statically determine that the value is already present.
Both tasks in that example returned a value, but thatâs not a requirement â the âfire and forgetâ approach allows us to create a task without storing it, and Swift will ensure it runs until completion correctly.
To demonstrate this, we could make a small SwiftUI program to fetch a userâs inbox when a button is pressed. Button actions are not async functions, so we need to launch a new task inside the action. The task can call async functions, but in this instance we donât actually care about the result so weâre not going to store the task â the function it calls will handle updating our SwiftUI view.
Hereâs the code:
struct Message: Decodable, Identifiable {
let id: Int
let from: String
let text: String
}
struct ContentView: View {
@State private var messages = [Message]()
var body: some View {
NavigationView {
Group {
if messages.isEmpty {
Button("Load Messages") {
Task {
await loadMessages()
}
}
} else {
List(messages) { message in
VStack(alignment: .leading) {
Text(message.from)
.font(.headline)
Text(message.text)
}
}
}
}
.navigationTitle("Inbox")
}
}
func loadMessages() async {
do {
let url = URL(string: "https://hws.dev/messages.json")!
let (data, _) = try await URLSession.shared.data(from: url)
messages = try JSONDecoder().decode([Message].self, from: data)
} catch {
messages = [
Message(id: 0, from: "Failed to load inbox.", text: "Please try again later.")
]
}
}
}
Even though that code isnât so different from the previous example, I still want to pick out a few things:
- Creating the new task is what allows us to start calling an async function even though the buttonâs action is a synchronous function.
- The lifetime of the task is not bound by the buttonâs action closure. So, even though the closure will finish immediately, the task it created will carry on running to completion.
- We arenât trying to read a return value from the task, or storing it anywhere. This task doesnât actually return anything, and doesnât need to.
I know itâs a not a lot of code, but between Task
, async/await, and SwiftUI a lot of work is happening on our behalf. Remember, when we use await
weâre signaling a potential suspension point, and when our functions resume they might be on the same thread as before or they might not.
In this case there are potentially four thread swaps happening in our code:
- All UI work runs on the main thread, so the buttonâs action closure will fire on the main thread.
- Although we create the task on the main thread, the work we pass to it will execute on a background thread.
- Inside
loadMessages()
we useawait
to load our URL data, and when that resumes we have another potential thread switch â we might be on the same background thread as before, or on a different background thread. - Finally, the
messages
property uses the@State
property wrapper, which will automatically update its value on the main thread. So, even though we assign to it on a background thread, the actual update will get silently pushed back to the main thread.
Best of all, we donât have to care about this â we donât need to know how the system is balancing the threads, or even that the threads exist, because Swift and SwiftUI take care of that for us. In fact, the concept of tasks is so thoroughly baked into SwiftUI that thereâs a dedicated task()
modifier that makes them even easier to use.