We all know that async / await was one of this year’s big announcements WWDC. It completely changes the way we interact with concurrent code. Instea

An introduction to synchronizing access with Swift’s Actors

submited by
Style Pass
2021-06-14 20:00:08

We all know that async / await was one of this year’s big announcements WWDC. It completely changes the way we interact with concurrent code. Instead of using completion handlers, we can await results in a non-blocking way. More importantly, with the new Swift Concurrency features, our Swift code is much safer and consistent than ever before.

For example, the Swift team built an all-new threading model that ensures your program doesn’t spawn more threads than there are CPU cores to avoid thread explosion. This is a huge difference from GCD where every call to async would spawn a new thread and the CPU had to give each of your threads some time to run which caused significant overhead due to a lot of context switching.

While all this is interesting, and makes our concurrent code much better, this post is not about Swift concurrency as a whole. Instead, I want to focus on a smaller feature called Actors.

An actor in Swift 5.5 is an object that isolates access to its mutable state. This means that anybody that wants to call a method on an actor where the method relies on mutable state, regardless of reading or writing, has to do so asynchronously.

Leave a Comment