Updating UI from background threads, simple threading in Swift 3 for iOS

So, you’ve been working on your iOS app, and ran into some issue where the UI was stuttering. You googled it, and after a few minutes on stack overflow, your code is now downloading images for your table view on a background thread.  Now it scrolls buttery smooth.  You worked out the kink where the wrong image ua appearing in the cells, and you think you’re out of the woods.

You move on, but after a while you see some weirdness in your app... Suddenly all animations stop working.

There's a weird warning in the console: 

"This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release."

This sounds ominous, but luckily for you, the fix is easy.

Any code that changes the UI needs to execute in the main thread. 

Even if you’re not explicitly creating a separate thread, there are some functions that will implicitly run code in a closure in a background thread. 

I deal with this with a pair of really simple swift functions that I include in my utility file for all my projects.

UI() and BG() 

Update: I'd previously been using "qos: .background", but some code seemed to get hung up when doing that. I resolved my problem by changing the priority of the background blocks to "qos: .default", but feel free to experiment if you want.

func BG(_ block: @escaping ()->Void) {
    DispatchQueue.global(qos: .default).async(execute: block)

func UI(_ block: @escaping ()->Void) {
    DispatchQueue.main.async(execute: block)

The usage couldn’t be simpler. 

UI() { 
    // everything in here will execute on the main thread

BG() { 
    // everything in here will execute in the background

No need to remember the Grand Central Dispatch functions, and the slightly odd looking functions stick out in your code so you don’t overlook them. 

Update: Swift actually allows you to omit the parentheses , so you can actually just do this:

UI {
    // Everything in here will execute on the main thread

BG {
    // Everything in here will execute in the background


You need to be a little careful, if you run too much of your code in the UI block, you defeat the purpose of running your code in the background in the first place.

Also, you need to keep in mind that the code in both of these blocks won’t necessarily run in sequence with the surrounding code. It’s likely the line after your block will run before the code in the block executes.  Be careful! 

Eventually, you’ll need to do something fancier with threading, but these two functions account for 99% of my threading needs. Anyone looking at it will know the intent right away too.