Skip to content

Category: Multithreading

Catch SwiftUI model updates from bad threads before they crash your app

It hasn’t yet been reflected in the official SwiftUI documentation (yay, betas), but the WWDC presentations and further guidance from Apple engineers have made it very clear about one point of SwiftUI: as with UIKit, you must send SwiftUI updates only from the main thread. The more things change…

The bad thing about this is that if you don’t make your updates on the main thread, you get away with it.

Most of the time.

The reality: updating the UI outside the main thread — in UIKit and in the newer SwiftUI — is going to be a source of hard to debug bugs, possible race conditions when updates are made to the UI, and at worst, app crashes.

Your BindableObjects may have many attributes, all that require you to do a willChange.send(). With so many places where your asynchronous code may need to trigger an update to your Views, what can you do to catch those missed main thread migrations before they become headaches? Xcode can save your sanity with its built-in Main Thread Checker debug functionality. Let’s walk through a basic example.