What are swift actors and how do I use them?

Generated on 7/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

Migrate your app to Swift 6

Migrate your app to Swift 6

Experience Swift 6 migration in action as we update an existing sample app. Learn how to migrate incrementally, module by module, and how the compiler helps you identify code that’s at risk of data races. Discover different techniques for ensuring clear isolation boundaries and eliminating concurrent access to shared mutable state.

A Swift Tour: Explore Swift’s features and design

A Swift Tour: Explore Swift’s features and design

Learn the essential features and design philosophy of the Swift programming language. We’ll explore how to model data, handle errors, use protocols, write concurrent code, and more while building up a Swift package that has a library, an HTTP server, and a command line client. Whether you’re just beginning your Swift journey or have been with us from the start, this talk will help you get the most out of the language.

Platforms State of the Union

Platforms State of the Union

Discover the newest advancements on Apple platforms.

What’s new in Swift

What’s new in Swift

Join us for an update on Swift. We’ll briefly go through a history of Swift over the past decade, and show you how the community has grown through workgroups, expanded the package ecosystem, and increased platform support. We’ll introduce you to a new language mode that achieves data-race safety by default, and a language subset that lets you run Swift on highly constrained systems. We’ll also explore some language updates including noncopyable types, typed throws, and improved C++ interoperability.

What’s new in SwiftUI

What’s new in SwiftUI

Learn how you can use SwiftUI to build great apps for any Apple platform. Explore a fresh new look and feel for tabs and documents on iPadOS. Improve your window management with new windowing APIs, and gain more control over immersive spaces and volumes in your visionOS apps. We’ll also take you through other exciting refinements that help you make expressive charts, customize and layout text, and so much more.