Global Actors in Swift Concurrency
Everywhere!
--
Introduced in Swift 5.5 along with Swift’s new concurrency model, global actors provide synchronization and ensure correct data access.
Let’s take a look.
Difficulty: Beginner | Easy | Normal | Challenging
This article has been developed using Xcode 14.2, and Swift 5.7.2
Prerequisites
- Be able to produce a “Hello, World!” SwiftUI project
It might be nice if you had some knowledge of:
- Actors are a conceptual model used to deal with concurrency
- Be familiar with @MainActor
Keywords and Terminology
@MainActor: is a Swift attribute used to indicate that a type or function must be executed on the main thread.
Global Actors: Singleton actors which can be used to provide synchronization and ensure correct data access in concurrent contexts
Singleton: A way of instantiation that guarantees that only one instance of a class is created
Is a global actor the same as a main actor?
Not quite.
@MainActor
is a predefined global actor in Swift and represents the main dispatch queue. @Mainactor
is predefined, and represents the main dispatch queue. Because of this, @MainActor
will usually be used for UI tasks that need to be run on the main queue.
We can create our own global actors.
@globalActor
struct CustomGlobalActor {
actor ActorType { }
static let shared: ActorType = ActorType()
}
class MyClass {
@MainActor
var uiProperty: String = "Hello, UI!"
@CustomGlobalActor
var customProperty: String = "Hello, Custom!"
@MainActor
func updateUIProperty(value: String) {
uiProperty = value
}
@CustomGlobalActor
func updateCustomProperty(value: String) {
customProperty = value
}
}
let myClass = MyClass()
await print(myClass.customProperty)