Concurrency in modern Swift with Async & Await in SwiftUI — Part 5

DevTechie
DevTechie
Published in
4 min readDec 26, 2022

--

Concurrency in modern Swift with Async & Await in SwiftUI — Part 5

In this part, we will learn to convert completion blocks from old APIs into newer async await versions.

Converting completion blocks into async await

Async and await were introduced in Swift 5.5 and before that, all of us were juggling between completion blocks, so it’s not a surprise that we have completion block code sitting in large quantities. With the new API calling completion block code inside async await, can be a bit challenging, so let’s try to build a solution for that too.

We will start by adding a completion block based API call to our web service.

class WebService {
func getCoffeeList() async throws -> [Coffee] {
let (data, _) = try await URLSession
.shared
.data(from: URL(string: "https://random-data-api.com/api/coffee/random_coffee?size=10")!)
return try JSONDecoder().decode([Coffee].self, from: data)
}

func getCoffeeOldWay(completion: @escaping (Result<[Coffee], Error>) -> Void) {
URLSession.shared.dataTask(with: URLRequest(url: URL(string: "https://random-data-api.com/api/coffee/random_coffee?size=10")!)) { data, response, error in

guard error == nil else {
completion(.failure(NSError(domain: "Error

--

--