Async Functions Are Coming to Swift

4 min read#Swift#iOS#Concurrency

Photo by Wesley Pribadi on Unsplash.

Old iOS developers remember the days when Objective C didn’t support blocks just yet. Async operations were a nightmare.

Blocks improved async operations, and when Swift appeared, closures were already natural for us. But to help us get through async calls, closures still have their pitfalls.

Fortunately, a new feature called the async function is coming to Swift, and it will make our lives much better.


What’s the Problem With Closures?

Closures are fine, really, and served us well over the years. But we all know that async + closures has its issues.


Pyramid of Doom

Let’s just take a look at the following snippet:

func processImageFromServer(completionBlock: (_ result: UIImage?) -> Void) {
    loadFileFromServer("myFile") { fileData in
        analyzFile(fileData) { imageData in
            decodeImage(imageData) { image in
                scaleDownImage(image) { newImage in
                    completionBlock(newImage)
                }
            }
        }
    }
}
 
 
processImageFromServer { image in
    self.updateUI(withNewImage: image)
}

We all know this example. It is called the Pyramid of Doom.

While using several nested closures seems like an elegant idea at first, it still leads to some problems.

One problem we all know when dealing with nested closures is error handling. Take a look at the following snippet:

func processImageFromServer(completionBlock: (_ result: UIImage?) -> Void) {
    loadFileFromServer("myFile") { fileData in
        guard let fileData = fileData else {
            completionBlock(nil)
            return
        }
        analyzFile(fileData) { imageData in
            decodeImage(imageData) { image in
                scaleDownImage(image) { newImage in
                    completionBlock(newImage)
                }
            }
        }
    }
}

Do you see the call for the completionBlock and the return statement afterward? Now, imagine you need to do that for each closure. Not only that, but you must not forget the return statement either. Otherwise, you may encounter some serious issues that are hard to follow.

Using an enum and a switch statement can result in even uglier and more complicated code. Don’t even get me started on throwing functions:

func processImageFromServer(completionBlock: (_ result: UIImage?) -> Void) {
    loadFileFromServer("myFile") { fileData in
        do {
            analyzFile(fileData) { imageData in
                do {
                    decodeImage(imageData) { image in
                        do {
                            scaleDownImage(image) { newImage in
                                completionBlock(newImage)
                            }
                        } catch {
                            completionBlock(nil)
                        }
                    }
                } catch {
                    completionBlock(nil)
                }
            }
        } catch {
            completionBlock(nil)
        }
    }
}

I think the point is clear by now.

Fortunately, things are about to change soon with the two best buddies: async and await.


Meet Async and Await

Async and await are not something new at all. Microsoft had those features for many years with .Net and JavaScript developers know this feature well.

Where Swift is concerned, developers proposed to add this feature for almost five years and it finally got approved.

This is how it looks:

func loadFileFromServer(string : String) async ->Data // this is the async declaration
 
let fileData = await loadFileFromServer("myFile") // this is the call.

That’s it? That’s it.

We add the word async before returning a value when declaring the function and await before calling it.

If it’s familiar to you somehow, that’s because it looks similar to declaring functions as throwing.

Now let’s see the code above with the new async/await mechanism:

func processImageFromServer(string : String) async ->UIImage {
    let fileData    = await loadFileFromServer(string)
    let imageData   = await analyzFile(fileData)
    let image       = await decodeImage(imageData)
    return image
}

Isn’t that simple?

Using await suspends the current thread and waits for an answer. This makes the code much more apparent and straightforward.


Something Sounds Weird

OK, so we know we can write async code that looks and behaves like synchronized code.

But when you think of it, something is weird…

We said that we have a new operator called await that suspends the current thread.

One of the most popular use cases for using async operations is not to block the UI thread. If the UI thread calls to an async function and uses await, it means the UI thread is now blocked! So, what’s the point?

Well, it doesn’t work like that exactly.

Apparently, there are two types of functions now:

  • One is the async function, marked with an async.
  • The other is the function that calls the async function and includes the await operator. That function has the @asyncHandler operator.

The “body” of the @asyncHandler function is suspended, but the function that calls the @asyncHandler function is not suspended and continues without waiting for a response.

I will try to explain that both in code and diagram:

Diagram showing how async function works

Now let’s see it in code:

func loadImage() async ->UIImage? {
        do {
            print("6")
            let imageData = try Data(contentsOf: URL(string: "https://images.radio.com/myImage.png")!)
            print("7")
            return UIImage(data: imageData)
        } catch {
            
        }
 
        return nil
    }
    
    @IBAction func tapped(_ sender: Any) {
        print("1")
        startLoadImage()
        print("2")
 
    }
    
    @asyncHandler func startLoadImage() {
        print("3")
        if let image = await loadImage() {
            print("4")
            DispatchQueue.main.async {
                self.imageView.image = image
            }
        }
        print("5")
    }

When the tapped() function is fired, the order of the print messages in the console looks like this:

1
2
3
6
7
4
5

And this is critical to understanding that functions containing the await keyword are much like completion blocks. When you call such a function, the run loop continues, and this way, the UI thread is not blocked.

A question: What if the @asyncHandler function returns a value? Well, this is an impossible situation. @asyncHandler cannot return values. They can only be void functions.


Summary

Async and await are great news for Swift developers. This is another step toward making Swift a modern language and simplifying life for all of us.

But since it’s a significant change from what we’re used to, we need to understand precisely how it works under the hood. Carefully read the code snippet above to fully absorb how to use it.


Originally published on Medium.

Be the first to like it

Comments

Leave a comment

Comments appear after they're approved.

All posts