TicTacFish: Implementing a game using distributed actors
At a glance
| Item | Summary |
|---|---|
| Purpose | Use distributed actors to take your Swift concurrency and actor-based apps beyond a single process. |
| App architecture | A Swift sample bundle with entry-bearing project variants Step 0 Offline Local Only, Step 1 Distributed yet still Local Bot, Step 2 Distributed Remote Bot, Step 3 Distributed Local Network Player, each leading to Distributed APIs. |
| Main patterns | Model-View-ViewModel, Protocol-oriented abstraction, Publisher-backed observable state, Actor isolation |
| Project style | 76 scanned source file(s) across Swift, organized around ranked entry, type, and file boundaries. |
| Execution model | Source-visible boundaries: async declaration or closure, @MainActor, Task closure isolated to MainActor, Task, actor; none alone proves a background thread. |
| State/event model | Source-visible mechanisms: SwiftUI state property wrapper, ObservableObject, @Published. |
| Key frameworks/packages | Distributed, SwiftUI, Foundation, TicTacFishShared, Network, Remote package https://github.com/apple/swift-nio.git, Remote package https://github.com/apple/swift-nio-transport-services.git; these are source dependencies, not architecture labels. |
Project structure
Source bundle/
├── Step 2 Distributed Remote Bot/
│ ├── Server/
│ │ └── Sources/
│ │ └── TicTacFishServer/
│ │ └── boot.swift
│ ├── App/
│ │ └── TicTacFish/
│ │ └── TicTacFish/
│ │ └── TicTacFishApp.swift
│ └── Shared/
│ └── Sources/
│ └── TicTacFishShared/
│ ├── ActorSystems/
│ │ └── WebSocket/
│ │ └── WebSocketActorSystem.swift
│ └── ViewModel/
│ └── GameViewModel.swift
├── Step 0 Offline Local Only/
│ └── App/
│ └── TicTacFish/
│ └── TicTacFish/
│ ├── TicTacFishApp.swift
│ └── GameView.swift
├── Step 1 Distributed yet still Local Bot/
│ └── App/
│ └── TicTacFish/
│ └── TicTacFish/
│ └── TicTacFishApp.swift
├── Step 3 Distributed Local Network Player/
│ └── App/
│ └── TicTacFish/
│ └── TicTacFish/
│ └── TicTacFishApp.swift
└── Configuration/
└── SampleCode.xcconfig
Structure observations
- Architecturally prominent files are ranked from entry points and role-named declarations; resource-only paths are omitted.
- Primary languages: Swift.
- The verified tree contains 26 project/configuration file(s) and 111 source declaration(s).
Overall architecture
flowchart LR
Bundle["Sample bundle"]
V1["Step 0 Offline Local Only"]
V2["Step 1 Distributed yet still Local Bot"]
V3["Step 2 Distributed Remote Bot"]
V4["Step 3 Distributed Local Network Player"]
Boundary["Distributed APIs"]
Bundle --> V1
V1 --> Boundary
Bundle --> V2
V2 --> Boundary
Bundle --> V3
V3 --> Boundary
Bundle --> V4
V4 --> Boundary
Reference code
Step 2 Distributed Remote Bot/Server/Sources/TicTacFishServer/boot.swift:17 — architecture anchor
@main
struct Boot {
static func main() {
let system = try! WebSocketActorSystem(mode: .serverOnly(host: "localhost", port: 8888))
system.registerOnDemandResolveHandler { id in
// We create new BotPlayers "ad-hoc" as they are requested for.
// Subsequent resolves are able to resolve the same instance.
if system.isBotID(id) {
return system.makeActorWithID(id) {
OnlineBotPlayer(team: .rodents, actorSystem: system)
}
}
return nil // don't resolve on-demand
}
print("========================================================")
print("=== TicTacFish Server Running on: ws://\(system.host):\(system.port) ==")
print("========================================================")
Thread.sleep(forTimeInterval: 100_000)
print("Done.")
}
}Interpretation
The branches represent separate entry-bearing project variants in the downloaded bundle, not runtime calls between those variants. Each branch is intentionally collapsed at the documented framework boundary; the detailed target-local flow remains in the cited files. Ownership is claimed only where the next section cites a stored property or assignment.
Ownership and state
classDiagram
GameView *-- GameViewModel : model
GameView o-- GameMode : mode
GameView o-- OfflinePlayer : player
GameView o-- Model : _model
Ownership evidence
Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameView.swift:13 — stored dependency or nearest verified ownership anchor
struct GameView: View {
// ...
@StateObject private var model: GameViewModel
// ...
}| Owner | Object or state | Relationship | Mutation authority |
|---|---|---|---|
GameView |
GameViewModel (model) |
owns wrapper-managed state | Owning lexical scope |
GameView |
GameMode (mode) |
stores or receives | Initialized by the owner; the binding is immutable |
GameView |
OfflinePlayer (player) |
stores or receives | Initialized by the owner; the binding is immutable |
GameView |
Model (_model) |
stores or receives | App/module collaborators |
Composition arrows indicate a source-visible construction expression or locally owned value state; aggregation means the owner stores or receives a dependency without proving exclusive lifetime ownership.
Concurrency, scheduling, and thread safety
Evidence limit: actor isolation, async/await, or Task creation does not by itself prove background-thread execution; Sendable conformance alone does not prove thread-safe mutation.
| Concern | Source mechanism | Verified placement or handoff | Evidence |
|---|---|---|---|
| Suspension boundary | async declaration or closure |
The source declares or crosses an asynchronous boundary; it does not by itself establish background execution. | Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameFieldView.swift:16 |
| Main isolation | @MainActor |
The cited annotation marks its attached declaration or closure as main-actor isolated. | Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameFieldView.swift:35 |
| Main isolation | Task closure isolated to MainActor |
The cited operation explicitly enters a main-actor-isolated region. | Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameFieldView.swift:35 |
| Task creation | Task |
The source creates an unstructured task; surrounding context determines inherited actor isolation. | Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameFieldView.swift:35 |
| Actor isolation | actor |
The cited type is actor-isolated; this does not select a background thread. | Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameView.swift:34 |
@MainActor/MainActor.run, DispatchQueue.main, and RunLoop.main are reported as distinct isolation, queue, and event-loop mechanisms. A plain Task is kept separate from Task.detached; neither is labeled as a background thread.
Reference code
Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameFieldView.swift:16 — representative execution boundary
struct GameFieldView: View {
// ...
let action: (Int) async throws -> Void
// ...
}State propagation, frameworks, and dependencies
Evidence limit: an import proves a source-level compilation dependency at the cited line; it does not prove runtime use, architectural adoption, or whether a Swift package is a direct application dependency.
| Category | Mechanism or module | Verified role | Evidence |
|---|---|---|---|
| State propagation | SwiftUI state property wrapper |
A SwiftUI property wrapper supplies or observes UI state. | Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameFieldView.swift:13 |
| State propagation | ObservableObject |
ObservableObject supplies an observation contract. | Step 0 Offline Local Only/Shared/Sources/TicTacFishShared/ViewModel/GameViewModel.swift:12 |
| State propagation | @Published |
A published property can emit owner-controlled changes. | Step 0 Offline Local Only/Shared/Sources/TicTacFishShared/ViewModel/GameViewModel.swift:22 |
| Package manifest | Remote package https://github.com/apple/swift-nio.git |
The manifest declares a remote URL or registry dependency; direct target use and transitive position are not inferred. | Step 0 Offline Local Only/Shared/Package.swift:37 |
| Package manifest | Remote package https://github.com/apple/swift-nio-transport-services.git |
The manifest declares a remote URL or registry dependency; direct target use and transitive position are not inferred. | Step 0 Offline Local Only/Shared/Package.swift:38 |
| Source import | Distributed |
The cited file imports this module; runtime use and architectural role are not inferred. | Step 0 Offline Local Only/App/TicTacFish/TicTacFish/Globals.swift:8 |
| Source import | SwiftUI |
The cited file imports this module; runtime use and architectural role are not inferred. | Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameFieldView.swift:8 |
| Source import | Foundation |
The cited file imports this module; runtime use and architectural role are not inferred. | Step 0 Offline Local Only/Shared/Sources/TicTacFishShared/ActorSystems/ActorIdentity.swift:8 |
receive(on:) describes downstream delivery scheduling, while subscribe(on:) describes upstream subscription/request/cancel scheduling. An import Combine alone establishes neither behavior nor a Store, reducer, Redux, or other application architecture.
Class and protocol design
Step 1 Distributed yet still Local Bot/Shared/Sources/TicTacFishShared/Game/Players.swift:42 — representative type boundary
public protocol GamePlayer: AnyActor, Identifiable where ID == ActorIdentity {
// ...
func makeMove() async throws -> GameMove
// ...
}| Type | Responsibility | Depends on or conforms to |
|---|---|---|
TicTacFishApp |
Application entry and top-level composition | App |
TicTacFishApp |
Application entry and top-level composition | App |
TicTacFishApp |
Application entry and top-level composition | App |
TicTacFishApp |
Application entry and top-level composition | App |
GamePlayer |
Defines a capability or collaboration contract | AnyActor, Identifiable |
GamePlayer |
Defines a capability or collaboration contract | Sendable, Identifiable |
GamePlayer |
Defines a capability or collaboration contract | DistributedActor, Codable |
WebSocketActorSystem |
Runs entity-component-system update logic | DistributedActorSystem |
WebSocketActorSystemResultHandler |
Handles callbacks or feature events | DistributedTargetInvocationResultHandler |
BonjourResultHandler |
Handles callbacks or feature events | Distributed.DistributedTargetInvocationResultHandler |
The source explicitly defines local protocol relationships: RandomPlayerBotAI → PlayerBotAI, RandomPlayerBotAI → PlayerBotAI, OfflinePlayer → GamePlayer, RandomPlayerBotAI → PlayerBotAI, OfflinePlayer → GamePlayer, OnlineBotPlayer → GamePlayer.
Access control
| Symbol | Access | Verified effect | Likely rationale |
|---|---|---|---|
model (Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameFieldView.swift:13) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: keep state mutation or dependency lifetime inside the owning implementation. |
model (Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameView.swift:13) |
private |
Use is restricted to the lexical declaration and same-file extensions allowed by Swift. | Inference: keep state mutation or dependency lifetime inside the owning implementation. |
GameView (Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameView.swift:41) |
public |
The symbol is visible to importing modules. | Inference: make the declaration available across a module or target boundary. |
makeMove (Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameView.swift:46) |
public |
The symbol is visible to importing modules. | Inference: make the declaration available across a module or target boundary. |
Reference code
Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameFieldView.swift:13 — representative boundary
struct GameFieldView: View {
// ...
@StateObject private var model: GameViewModel
// ...
}Swift declarations without a modifier are internal; explicit private, fileprivate, private(set), public, or open entries above are interpreted by language semantics. Objective-C/C samples instead rely on header and implementation boundaries, which are not equivalent to Swift lexical privacy.
Logic ownership and placement
| Logic | Owning type or file | Placement rationale |
|---|---|---|
| Application entry and top-level composition | TicTacFishApp |
The source’s App suffix makes this role explicit. |
| Handles callbacks or feature events | BonjourResultHandler, HTTPHandler, HTTPInitialRequestHandler, WebSocketActorMessageInboundHandler |
The source’s Handler suffix makes this role explicit. |
| Owns media or timeline playback | BotPlayer, GamePlayer, LocalNetworkPlayer, OfflinePlayer |
The source’s Player suffix makes this role explicit. |
| Runs entity-component-system update logic | WebSocketActorSystem |
The source’s System suffix makes this role explicit. |
| User-interface presentation and input forwarding | GameFieldView, GameView, MainMenuView, TitleView |
The source’s View suffix makes this role explicit. |
| UI-facing state and feature coordination | GameViewModel |
The source’s ViewModel suffix makes this role explicit. |
Design patterns
| Pattern | Source evidence | Purpose or tradeoff |
|---|---|---|
| Model-View-ViewModel | Step 0 Offline Local Only/Shared/Sources/TicTacFishShared/ViewModel/GameViewModel.swift:12 |
Role-named view models keep UI-facing state or coordination outside view declarations. |
| Protocol-oriented abstraction | Step 0 Offline Local Only/Shared/Sources/TicTacFishShared/Game/PlayerBotAI.swift:23 |
A local protocol and concrete conformance create an explicit capability boundary. |
| Publisher-backed observable state | Step 0 Offline Local Only/Shared/Sources/TicTacFishShared/ViewModel/GameViewModel.swift:22 |
Published properties notify observers while mutation remains with the state object. |
| Actor isolation | Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameView.swift:34 |
A declared actor creates an explicit isolation boundary; its executor is not described as a background thread. |
Main application flow
sequenceDiagram
participant WebSocketActorSystem
participant Task
participant _openExistential
participant handler
WebSocketActorSystem->>Task: Start asynchronous work
WebSocketActorSystem->>WebSocketActorSystem: executeDistributedTarget()
WebSocketActorSystem->>_openExistential: _openExistential()
WebSocketActorSystem->>handler: onThrow()
Reference code
Step 2 Distributed Remote Bot/Shared/Sources/TicTacFishShared/ActorSystems/WebSocket/WebSocketActorSystem.swift:373 — receiveInboundCall()
func receiveInboundCall(envelope: RemoteWebSocketCallEnvelope, on channel: Channel) {
// ...
log("receive-inbound", "Envelope: \(envelope)")
Task {
log("receive-inbound", "Resolve any: \(envelope.recipient)")
guard let anyRecipient = resolveAny(id: envelope.recipient, resolveReceptionist: true) else {
log("deadLetter", "[warn] \(#function) failed to resolve \(envelope.recipient)")
return
}
log("receive-inbound", "Recipient: \(anyRecipient)")
let target = RemoteCallTarget(envelope.invocationTarget)
log("receive-inbound", "Target: \(target)")
log("receive-inbound", "Target.identifier: \(target.identifier)")
let handler = ResultHandler(actorSystem: self, callID: envelope.callID, system: self, channel: channel)
log("receive-inbound", "Handler: \(anyRecipient)")
do {
var decoder = Self.InvocationDecoder(system: self, envelope: envelope)
func doExecuteDistributedTarget<Act: DistributedActor>(recipient: Act) async throws {
log("receive-inbound", "executeDistributedTarget")
try await executeDistributedTarget(
on: recipient,
target: target,
invocationDecoder: &decoder,
handler: handler)
}
try await _openExistential(anyRecipient, do: doExecuteDistributedTarget)
} catch {
log("inbound", "[error] failed to executeDistributedTarget [\(target)] on [\(anyRecipient)], error: \(error)")
try! await handler.onThrow(error: error)
}
}
}Naming conventions
- Types: App: TicTacFishApp; Handler: BonjourResultHandler, HTTPHandler, HTTPInitialRequestHandler, WebSocketActorMessageInboundHandler, WebSocketActorSystemResultHandler; Player: BotPlayer, GamePlayer, LocalNetworkPlayer, OfflinePlayer, OnlineBotPlayer; System: WebSocketActorSystem; View: GameFieldView, GameView, MainMenuView, TitleView; ViewModel: GameViewModel.
- Protocols:
GamePlayer,GamePlayer,GamePlayer,PlayerBotAI,PlayerBotAI,PlayerBotAI,PlayerBotAI,DistributedActorReceptionist. - Methods:
main,syncShutdownGracefully,assignID,actorReady,resignID,resolve,resolveAny,makeInvocationEncoder. - Files:
Step 0 Offline Local Only/App/TicTacFish/TicTacFish/TicTacFishApp.swift,Step 1 Distributed yet still Local Bot/App/TicTacFish/TicTacFish/TicTacFishApp.swift,Step 2 Distributed Remote Bot/App/TicTacFish/TicTacFish/TicTacFishApp.swift,Step 3 Distributed Local Network Player/App/TicTacFish/TicTacFish/TicTacFishApp.swift,Step 2 Distributed Remote Bot/Shared/Sources/TicTacFishShared/ActorSystems/WebSocket/WebSocketActorSystem.swift,Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameView.swift.
Architecture takeaways
bootis the main source-visible entry or composition anchor for this sample.- Framework work reaches Distributed, SwiftUI, TicTacFishShared, NIOCore through a deliberately small high-level chain; the detailed API graph remains inside the cited implementation files.
- Stored-property evidence identifies lifecycle collaboration; it does not by itself prove exclusive object ownership.
- Access-control conclusions separate verified language visibility from the likely design rationale.
- Local protocol relationships provide an explicit substitution boundary.
Source map
| Source file | Relevant symbols |
|---|---|
Step 2 Distributed Remote Bot/Server/Sources/TicTacFishServer/boot.swift |
Cited implementation, Boot |
Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameView.swift |
Cited implementation, OfflinePlayer, actor, GameView, GameView_Previews |
Step 1 Distributed yet still Local Bot/Shared/Sources/TicTacFishShared/Game/Players.swift |
GamePlayer, BotPlayer, OfflinePlayer |
Step 0 Offline Local Only/App/TicTacFish/TicTacFish/GameFieldView.swift |
Cited implementation, async declaration or closure, @MainActor, Task closure isolated to MainActor, Task, SwiftUI state property wrapper, SwiftUI, GameFieldView |
Step 0 Offline Local Only/Shared/Sources/TicTacFishShared/ViewModel/GameViewModel.swift |
GameViewModel, Cited implementation, ObservableObject, @Published |
Step 0 Offline Local Only/Shared/Sources/TicTacFishShared/Game/PlayerBotAI.swift |
Cited implementation, PlayerBotAI, BotAIDifficulty, RandomPlayerBotAI, NoMoveAvailable |
Step 0 Offline Local Only/Shared/Package.swift |
Cited implementation, Feature implementation |
Step 0 Offline Local Only/App/TicTacFish/TicTacFish/Globals.swift |
Distributed, Feature implementation |
Step 0 Offline Local Only/Shared/Sources/TicTacFishShared/ActorSystems/ActorIdentity.swift |
Foundation, ActorIdentity |
Step 0 Offline Local Only/App/TicTacFish/TicTacFish/TicTacFishApp.swift |
TicTacFishApp |
Step 1 Distributed yet still Local Bot/App/TicTacFish/TicTacFish/TicTacFishApp.swift |
TicTacFishApp |
Step 2 Distributed Remote Bot/App/TicTacFish/TicTacFish/TicTacFishApp.swift |
TicTacFishApp |
Step 3 Distributed Local Network Player/App/TicTacFish/TicTacFish/TicTacFishApp.swift |
TicTacFishApp |
Step 2 Distributed Remote Bot/Shared/Sources/TicTacFishShared/ActorSystems/WebSocket/WebSocketActorSystem.swift |
WebSocketWireEnvelope, RemoteWebSocketCallEnvelope, WebSocketActorSystemMode, WebSocketActorSystem, WebSocketActorSystemResultHandler, WebSocketActorSystemError |
Step 3 Distributed Local Network Player/Shared/Sources/TicTacFishShared/ActorSystems/LocalNetwork/LocalNetworkActorSystem.swift |
BonjourResultHandler, SampleLocalNetworkActorSystemError, NetworkServiceConstants, Peer, RemoteCallEnvelope, ReplyEnvelope |
Step 1 Distributed yet still Local Bot/Shared/Sources/TicTacFishShared/ViewModel/GameViewModel.swift |
GameViewModel |