DEV Community

Robertino
Robertino

Posted on

📲 Async Await in Swift

A Guide to fully understand the new concurrency system in Swift.


This year, WWDC came with a bunch of new features and updates. Maybe one of the most expected was the introduction of the new concurrency system by using async/await syntax. This is a huge improvement in the way that we write asynchronous code.

Before Async/Await

Imagine that we are working on an app for a grocery store and, we want to display its list of products. We are probably going to have something like this:

func fetchProducts(_ completion: @escaping([Product]) -> Void) {...}

var products = [Product]()
fetchProducts { [weak self] products in
    guard let strongSelf = self else { return }
    strongSelf.products.append(contentsOf: products)
}
Enter fullscreen mode Exit fullscreen mode

A pretty standard and well-known code using completion blocks. Now suppose that the grocery store has, once in a while, some kind of offers for some products (e.g., "Take 2, pay 1"). And, we want to hold a list with these offers. Let's adjust our code by creating a new function to retrieve a String with the promotion text, given a specific product.

func fetchProducts(_ completion: @escaping([Product]) -> Void) {...}
func getOffer(for product: Int, @escaping(String) -> Void) {...}

typealias ProductOffer = (productId: Int, offer: String)
var products = [Product]()
var offers = [ProductOffer]()

fetchProducts { [weak self] products in
    guard let strongSelf = self else { return }

    for product in products {
        strongSelf.products.append(product)

        getOffer(for: product.id) { [weak self] offerText in
            guard let strongSelf = self else { return }
            let productOffer = ProductOffer(productId: product.id, offer: offerText)
            strongSelf.offers.append(productOffer)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

We only have two nested closures for a simple feature, and you can see that our code starts to get a little messed up.

Read more

Discussion (0)