Actors— Swift — A Quick Introduction

Sudhanshu Srivastava
1 min readSep 11, 2024

--

Photo by Nik on Unsplash

What are actors?
Actors are reference types like classes hence all the conditions which apply to classes are also applicable to actors. Just with exception i.e. Actors allow only one task to access their mutable state at a time which makes it safe for code in multiple tasks.

How to define?
Defining an actor is same as class, just use keyword actor instead of class.

How to access properties or call a methods of an actor?
As per the definition above actors allow only one task to access their mutable state at a time to access a property you need to use await keyword to mark potential suspension point. If some other code is interacting with the the actor instance then this code suspends and waits to access the property. If you don’t use await the compiler will throw an error.
Note: Inside actor it doesn’t need to use await to access its own property or call its own methods. Swift guarantees that the only code running on an actor can access that actor’s local state (known as actor isolation).

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Sudhanshu Srivastava
Sudhanshu Srivastava

Written by Sudhanshu Srivastava

I write about what I learn. Swift, Kotlin, Flutter, Social and Life.

No responses yet

Write a response