Goodbye completion handlers and Dispatch.main.async.

Tom Zurkan
2 min readJul 25, 2023

I may be a little late to this party. But, I was implementing an application and started to use the old tried and true completion handler approach. After I had completed the task, I looked over the work again and wondered what it would take to convert to async await. Not only was it trivial to convert, it looks so much cleaner I had to say goodbye to completion handlers. Of course, if you still need to maintain compatability with Objective-C then you will have to wait. If you are providing APIs, I still feel like it is a good idea to provide both options like URLSession does.

So, let’s take a look at what the old style of code looks like on a view controller. Of course, if you are using SwiftUI then the allure for async await should be too much to bare. But, if you have some old code or are still using UIKit, read on.

You can see in the first loadPhoto.swift file that we are using a completion handler. It returns not on the main thread and then we call dispatch main async to get back on the main thread and set the image. We have to worry about threading and locking resources. Note: The completion handler could have switched to main thread before calling but I think that is not a good design approach. Now, enter the unstructured concurrency. We simply wrap the await in a task and the rest is done for you. You can mark shared resouces with actor. It doesn’t look much different nested in a do catch but to me it looks so much more elegant and straight forward.

I won’t touch on main actor too much, but, it is a nice way to coordinate resources that are immediately thread safe.

I think that this is great leap for Swift and I am late to the party because it has been around for a couple of years. But, it didn’t seem well thought out when async/await first arrived. You have to laugh at the fact that async await seems borrowed from java script. It makes me wonder who is driving the Swift evolution. That said, both python and typescript seem to follow swift style syntax. Anyway, the ramblings of an engineer. Happy Coding!

--

--

Tom Zurkan

Engineer working on full stack. His interests lie in modern languages and how best to develop elegant crash proof code.