What are swift actors and how do I use them?

Asked on 07/31/2024

1 search

Swift actors are a feature introduced to help manage concurrency in Swift by protecting shared mutable state. They are similar to classes in that they are reference types, but they automatically serialize access to their state, ensuring that only one task can execute at a time on an actor. This helps prevent data races and makes concurrent programming safer and more manageable.

How to Use Swift Actors

  1. Define an Actor: You can define an actor similarly to how you define a class.

    actor UserStore {
        var users: [String] = []
        
        func addUser(_ user: String) {
            users.append(user)
        }
        
        func getUsers() -> [String] {
            return users
        }
    }
    
  2. Accessing Actor Methods: Calls to actor methods from outside the actor are asynchronous, so you need to use the await keyword.

    let userStore = UserStore()
    
    Task {
        await userStore.addUser("Alice")
        let users = await userStore.getUsers()
        print(users)
    }
    
  3. Concurrency Safety: By using actors, you ensure that accesses to the actor's state are serialized, preventing data races.

    actor UserStore {
        var users: [String] = []
        
        func addUser(_ user: String) {
            users.append(user)
        }
        
        func getUsers() -> [String] {
            return users
        }
    }
    
    let userStore = UserStore()
    
    Task {
        await userStore.addUser("Alice")
        let users = await userStore.getUsers()
        print(users)
    }
    

For more detailed information, you can refer to the session A Swift Tour: Explore Swift’s features and design which covers the basics of writing concurrent code in Swift, including tasks, async/await, and actors.

Relevant Sessions

What are swift actors and how do I use them? | Ask WWDC