Discover async / await in Swift
You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿
You’ve heard that async
/ await
is amazing with asynchronous code, but you're not really sure how it works? 🤨
Don’t worry! I’ve got you covered! 😌
In just a few paragraphs we’ll go over everything you need to know to understand how this powerful tool works!
Let’s start by talking about functions!
In Swift there are two kind of functions.
First, we have the functions that don’t need to wait on anything to compute their results:
Even though these functions can take a long time to compute their result, they’re able to compute it without needing to take a pause while they execute.
We call these functions synchronous functions:
But there is also another kind of functions: the functions that do need to take a pause during their execution, in order to wait for an external event to complete.
We call these functions asynchronous functions 🤨
A typical example would be a function that needs to await for a network call to complete:
In order to clearly indicate that the function will pause until the network call completes, we use the keyword await
at the call site:
We also need to update the signature of the function with the keyword async
to indicate that the function is allowed to take a pause during its execution:
The big difference between synchronous and asynchronous functions is that, since asynchronous functions can pause during their execution, we are only allowed to call them in specific places.
We can call an async
function either from within another async
function:
Or from within a Task
that will be executed in the background:
And that’s it, we’ve covered the basics of how async
/ await
works in Swift!
Thanks to these two keywords, we are now able to deal with asynchronous code in a way that is both very safe and very readable 👌
Here’s the code if you want to experiment with it:
// Synchronous functions
func add(_ first: Int, _ second: Int) -> Int {
return first + second
}
func longToExecute() -> Int {
var result = 0
for i in 0...1_000_000 {
result += i
}
return result
}
// Asynchronous function
func loadFromNetwork() async -> Data {
let url = URL(string: "https://myapi.com/endpoint")!
let (data, _) = try! await URLSession.shared.data(from: url)
return data
}
// Calling `async` functions
func anAsyncFunction() async {
await anotherAsyncFunction()
}
func aSynchronousFunction() {
Task {
await anAsyncFunction()
}
}