0
0
Swiftprogramming~5 mins

Distributed actors overview in Swift

Choose your learning style9 modes available
Introduction

Distributed actors help your program talk to parts running on other computers easily and safely.

You want to build a chat app where users connect from different devices.
You need to run tasks on multiple servers and collect results.
You want to share data between apps running on different machines.
You are making a game where players connect over the internet.
You want to split work across several computers to speed up processing.
Syntax
Swift
distributed actor ActorName {
    // actor code here
}
Use the keyword distributed actor to define a distributed actor.
Distributed actors can send and receive messages across the network automatically.
Examples
This defines a distributed actor named ChatUser with a function to send messages.
Swift
distributed actor ChatUser {
    distributed func sendMessage(_ message: String) async
}
A distributed actor Calculator that can add two numbers remotely.
Swift
distributed actor Calculator {
    distributed func add(_ a: Int, _ b: Int) async -> Int {
        return a + b
    }
}
Sample Program

This program defines a distributed actor Greeter with a function to greet someone by name. It then creates an instance and calls the greet function, printing the result.

Swift
import Distributed

// Define a distributed actor
distributed actor Greeter {
    distributed func greet(name: String) async throws -> String {
        return "Hello, \(name)!"
    }
}

// Simulate calling the distributed actor
@main
struct Main {
    static func main() async throws {
        let greeter = Greeter()
        let message = try await greeter.greet(name: "Friend")
        print(message)
    }
}
OutputSuccess
Important Notes

Distributed actors require Swift concurrency features like async/await.

They handle communication details so you can focus on your app logic.

Behind the scenes, calls to distributed functions may go over the network.

Summary

Distributed actors let your code work across multiple computers easily.

Use distributed actor to define them and distributed func for remote calls.

They simplify building apps that communicate over a network.