Modern Concurrency with async/await in Swift. Part - 1.

Rahul Patel
Globant
Published in
2 min readJan 31, 2022

Plot: We are going to have a basic introduction for async/await.

Earlier, we used to have completions while downloading an image from the web and also needed to take care that must be returned in the main thread & also needed to write completion in any case. If we forget, the calling function will not have any idea about the result.

like below code snippet

To overcome those headaches, swift introduces the async/await keyword in swift 5.5

How to define async functions?

func getImage() async -> UIImage {
let result= // your async network call here with await keyword.
return image
}

for Ex

Async means it enables to suspend a task & hand over its execution to the system, then the system decides when to resume this task.

Await means the system will know from where to suspend the task & to perform other important tasks.

We just need to mark an async function as await while calling it.

Once the awaited call completes, then it will start execution after the await.

In the above example URLSession.shared.data method is an async method. which returns the image data & response.

Execution will suspend at URLSession.shared.data method, as it is awaited call. As URLSession completes its task, the system will automatically resume function execution onwards & return the image in sync.

For in-depth knowledge of Async/Await watch this WWDC video
https://developer.apple.com/videos/play/wwdc2021/10132/

Here is part 2 (Understanding Task).
https://medium.com/@rahul.patel_41877/modern-concurrency-with-async-await-in-swift-task-part-2-c0f1abe6e1e0

--

--