How to create and use a global actor in Swift

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

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 11/01/2023 at 08:58
Last Updated on 11/01/2023 at 09:24
<p>Two flowers that represent Swift and Xcode. Beneath them sits the text "Global Actor."</p>

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

SubscribeDownload Open Source Starter Project

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.

View Repository

Step One: Create the Global Actor

<p>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.</p>

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

<p>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.</p>

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.

How to use async await in Swift projects

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.

Search our Blog

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.
SubscribeContact UsVisit our BlogView our ServicesView our Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe