How to create and use a global actor in Swift

Oscar de la Hera Gomez
Two flowers that represent Swift and Xcode. Beneath them sits the text "Global Actor."

A step by step tutorial on creating a global actor in Swift. Github repository included.

The following tutorial walks you through how to create a global actor through the lens of our NotificationCoordinator - a singleton intended to act as the center for sending type-checked notifications.

This singleton is available as part of our Open Source Swift Starter Project that is available in the link below.

Step One: Create the Global Actor

A screenshot of Xcode showing the functionality for the NotificationCoordinator that is available as part of our Open Source Swift Starter Project. We have highlighted that the singleton has a @globalActor annotation and that it is of type actor. Highlighted is that it also uses a shared variable.

Create a singleton class and :

  • Replace the class attribute with actor.
  • Assign the @globalActor annotation to make it conform to the protocol.
  • Make sure that it has a shared property that acts as the singleton.

Subsequently, create any additional functionality that may be required. We recommend you do this in extensions that separate code into specific functionality.

Step Two: Wrap Functionality in a Task

A screenshot of Xcode showing how all async/await functionality, such as any functionality of variables used in actors, must be wrapped in a Task for it to conform to concurrency.

As a Global Actor must conform to concurrency, every action that you take with it must be wrapped in a task and must use async/await.

Looking to learn more about things you can do with Swift and XCode ?

Search our blog to find educational content on learning how to use Swift and XCode.

Any Questions?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.
delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details