what actor does a task run on

Generated on 8/3/2024

1 search

A task runs on the actor it is associated with. In Swift, actors are reference types that encapsulate shared mutable state and automatically protect their state by serializing accesses. Only a single task is allowed to execute at a time on an actor, and calls to actor methods from outside the context of the actor are asynchronous.

For example, if you have a method that is isolated to the main actor, it means that the method will run on the main actor. This can be explicitly stated using mainactor assume isolated, which tells Swift that the code is already running on the main actor and does not start a new task to async onto the main actor.

Here are some relevant sessions and timestamps that discuss actors and tasks:

  1. A Swift Tour: Explore Swift’s features and design - Discusses how actors serialize accesses and ensure that only a single task executes at a time on an actor.
  2. Migrate your app to Swift 6 - Explains the use of mainactor assume isolated to indicate that code is running on the main actor without starting a new task.
  3. Migrate your app to Swift 6 - Describes how methods can be isolated to the main actor and how to handle asynchronous calls to actor-isolated state.

Relevant Sessions

  1. Migrate your app to Swift 6
  2. A Swift Tour: Explore Swift’s features and design