BLACK FRIDAY SALE: Save big on all my Swift books and bundles! >>

Important: Do not use an actor for your SwiftUI data models

Paul Hudson    @twostraws   

Updated for Xcode 14.0 beta 1

Swift’s actors allow us to share data in multiple parts of our app without causing problems with concurrency, because they automatically ensure two pieces of code cannot simultaneously access the actor’s protected data.

Actors are an important addition to our toolset, and help us guarantee safe access to data in concurrent environments. However, if you’ve ever wondered “should I use an actor for my SwiftUI data?”, let me answer that as clearly as I can: actors are a really bad choice for any data models you use with SwiftUI – anything that conforms to the ObservableObject protocol.

SwiftUI updates its user interface on the main actor, which means when we make a class conform to ObservableObject we’re agreeing that all our work will happen on the main actor. As an example, any time we modify an @Published property that must happen on the main actor, otherwise we’ll be asking for changes to be made somewhere that isn’t allowed.

Now think about what would happen if you tried to use a custom actor for your data. Not only would any data writes need to happen on that actor rather than the main actor (thus forcing the UI to update away from the main actor), but any data reads would need to happen there too – every time you tried to bind a string to a TextField, for example, you’d be asking Swift to simultaneously use the main actor and your custom actor, which doesn’t make sense.

The correct solution here is to use a class that conforms to ObservableObject, then annotate it with @MainActor to ensure it does any UI work safely. If you still find that you need to be able to carve off some async work safely, you can create a sibling actor – a separate actor that does not use @MainActor, but does not directly update the UI.

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 1.0/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.