Using async let with synchronous code
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 🍿
I’m sure that you’ve already used async let
.
It’s a very powerful feature that lets you run several asynchronous functions concurrently, with very little additional syntax required:
But did you know that it has a hidden feature?
Take a look at this synchronous Swift function, that performs a computation that will take a few seconds to complete:
To run this function asynchronously, we could make the function async
or wrap its call site into a Task
.
However, there’s actually an even simpler solution.
And that’s because using async let
is not limited to asynchronous functions!
You can totally use this syntax to call a regular synchronous function:
And when you do, the execution of this function will be dispatched to a background thread!
The best part is that we didn’t had to make any change to the code of the function or to use error-prone APIs like a Task
.
That’s all for this article, as always I hope that you’ve enjoyed discovering this new trick!
Here’s the code if you want to experiment with it:
import Foundation
func performTimeConsumingTask() -> Int {
var result = 0
for i in 1...100_000_000 {
result += i
}
return result
}
async let result = performTimeConsumingTask()
print("result: \(await result)")