async/await in Swift
All the features you need to know about
We’ll cover:
async
functionsasync get
propertiesasync let
- Parallel execution using
withTaskGroup
andwithThrowingTaskGroup
- Legacy APIs and
withCheckedContinuation
andwithCheckedThrowingContinuation
- Create arrays of events or
AsyncSequence
withAsyncStream
actor
andnonisolated
and why we need them
Grab the code here 👊
Foundations
Why?
Let’s start with why. Why the hell do we need it? Have a look:
Boy, this looks ugly. And it’s a typical async code we had in our apps, until now.
The first async function
Let’s make it pretty with async/await, and you’ll see why we need it.
Let’s keep this ugly monster here and create a new function.
First, we have to mark the function as async
, it always goes before throws
:
Many Apple APIs now have async alternatives for the functions we know.
Instead of passing the result through a callback, the function simply returns it and errors are thrown. That’s something we do in our function, too:
Now, when we call a function like that, we have to await
it on the caller's side. It's done with await
keyword which always goes after try
. try
is needed here to catch errors.
Here we see a further benefit — now we can use throw to return from a function with an error. You can’t do it inside the callback!
image.byPreparingThumbnail
is just another async function provided for us by Apple. Nice!
Compare the 2 now. Which one is easier to read?
Let’s actually use the function now, let’s go to the ViewModel
and replace the old onAppear()
:
Now the function has to be marked async
, and we handle errors with a do/catch
block.
Let’s go to the view now!
'async' call in a function that does not support concurrency
screams at us!
How can we convert .onAppear {}
to be async? - We can't! We use Task
instead!
We dispatch a task (aka call an async function) this way from non-async
context. It's a bridge between async
and non-async
worlds (and not only that).
Let’s run the app now to see it work!
Not only functions (async get)
Btw. functions are not the only things that can be marked async. You can have async
get
properties now too!
Let’s use it in fetchThumbnail
:
Here’s our async/await series:
Part 1. (this one) async/await functions and async get
Part 2. async let and TaskGroup in Swift
Part 3. Convert legacy APIs to async/await
Part 4. How to use Async Sequence and AsyncStream in Swift
Part 5. Actors and Data Races in Swift