Swift actors: How do they work, and what kinds of problems do they solve?

Click for: original source

Since the very first version of Swift, we’ve been able to define our various types as either classes, structs, or enums. But now, with the launch of Swift 5.5 and its built-in concurrency system, a new type declaration keyword has been added to the mix – actor. By John Sundell.

One of the core advantages of Swift’s new actor types is that they can help us prevent so-called “data races” – that is, memory corruption issues that can occur when two separate threads attempt to access or mutate the same data at the same time.

So, in this article, let’s explore the concept of actors, and what kinds of problems that we could solve by defining custom actor types within our code bases. The article explains:

  • Preventing data races
  • A case for an actor
  • Race conditions are still possible

So, in general, actors are a fantastic tool when we want to implement a type that supports concurrent access to its underlying state in a very safe way. However, it’s also important to remember that turning a type into an actor will require us to interact with it in an asynchronous manner, which usually does make such calls somewhat more complex (and slower) to perform – even with tools like async/await at our disposal. Good read!

[Read More]

Tags swiftlang linux how-to programming learning