Sample CodevisionOSReviewed 2026-07-21View on Apple Developer

Tracking accessories in volumetric windows

At a glance

Item Summary
Purpose Translate the position and velocity of tracked handheld accessories to throw virtual balls at a stack of cans.
App architecture A Swift sample with the source-visible chain TrackingAccessoriesAppAccessoryTrackingViewAccessoryTrackingModelThrowSpeedTrackerARKit APIs.
Main patterns View-controller organization
Project style 13 scanned source file(s) across Swift, organized around ranked entry, type, and file boundaries.
Execution model Source-visible boundaries: @MainActor, Task closure isolated to MainActor, Task, await suspension point; none alone proves a background thread.
State/event model Source-visible mechanisms: @Observable, NotificationCenter, SwiftUI state property wrapper.
Key frameworks/packages RealityKit, ARKit, SwiftUI, GameController, Observation; these are source dependencies, not architecture labels.

Project structure

Source bundle/
└── TrackingAccessories/
    ├── TrackingAccessoriesApp.swift
    ├── Models/
    │   ├── SpatialController.swift
    │   ├── AccessoryTrackingModel.swift
    │   └── ThrowSpeedTracker.swift
    ├── Views/
    │   ├── AccessoryTrackingView.swift
    │   ├── AppStateView.swift
    │   └── GameStateView.swift
    └── Entities/
        ├── Arrow3D.swift
        ├── Ball.swift
        ├── Can.swift
        ├── CanStack.swift
        └── Crate.swift

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 4 project/configuration file(s) and 18 source declaration(s).

Overall architecture

Reference code

TrackingAccessories/TrackingAccessoriesApp.swift:12 — architecture anchor

@main
struct TrackingAccessoriesApp: App {
    var body: some SwiftUI.Scene {
        WindowGroup {
            AccessoryTrackingView()
        }
        .windowStyle(.volumetric)
    }
}

Interpretation

The arrows summarize the source-visible entry, role-named types or folders, and framework direction; when nodes come from structural folders, the sequence is a high-level interpretation rather than proof that every adjacent node calls the next. Ownership is claimed only where the next section cites a stored property or assignment. The diagram is intentionally limited to the dominant path into ARKit.

Ownership and state

Ownership evidence

TrackingAccessories/Models/SpatialController.swift:13 — stored dependency or nearest verified ownership anchor

@Observable
@MainActor
final class SpatialController {
    var anchor: AccessoryAnchor? = nil
    // ...
}
Owner Object or state Relationship Mutation authority
SpatialController AccessoryAnchor (anchor) stores or receives App/module collaborators
SpatialController Throw (pendingThrow) creates and retains App/module collaborators
SpatialController Throw (triggeredThrow) stores or receives App/module collaborators
SpatialController Shake (pendingShake) creates and retains 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
Main isolation @MainActor The cited annotation marks its attached declaration or closure as main-actor isolated. TrackingAccessories/Entities/Arrow3D.swift:10
Main isolation Task closure isolated to MainActor The cited operation explicitly enters a main-actor-isolated region. TrackingAccessories/Models/AccessoryTrackingModel.swift:97
Task creation Task The source creates an unstructured task; surrounding context determines inherited actor isolation. TrackingAccessories/Models/AccessoryTrackingModel.swift:97
Suspension boundary await suspension point The source declares or crosses an asynchronous boundary; it does not by itself establish background execution. TrackingAccessories/Models/AccessoryTrackingModel.swift:124

@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

TrackingAccessories/Entities/Arrow3D.swift:10 — representative execution boundary

@MainActor
class Arrow3D: Entity, HasModel {
    static private let shaftLength: Float = 1.0
    // ...
}

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 @Observable Observation macro publishes source-visible changes. TrackingAccessories/Models/AccessoryTrackingModel.swift:12
State propagation NotificationCenter NotificationCenter distributes named process-local events. TrackingAccessories/Models/AccessoryTrackingModel.swift:89
State propagation SwiftUI state property wrapper A SwiftUI property wrapper supplies or observes UI state. TrackingAccessories/Views/AccessoryTrackingView.swift:13
Source import RealityKit The cited file imports this module; runtime use and architectural role are not inferred. TrackingAccessories/Entities/Arrow3D.swift:8
Source import ARKit The cited file imports this module; runtime use and architectural role are not inferred. TrackingAccessories/Models/AccessoryTrackingModel.swift:8
Source import SwiftUI The cited file imports this module; runtime use and architectural role are not inferred. TrackingAccessories/TrackingAccessoriesApp.swift:8
Source import GameController The cited file imports this module; runtime use and architectural role are not inferred. TrackingAccessories/Models/AccessoryTrackingModel.swift:9
Source import Observation The cited file imports this module; runtime use and architectural role are not inferred. TrackingAccessories/Models/ThrowSpeedTracker.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

TrackingAccessories/TrackingAccessoriesApp.swift:13 — representative type boundary

@main
struct TrackingAccessoriesApp: App {
    // ...
            AccessoryTrackingView()
    // ...
}
Type Responsibility Depends on or conforms to
TrackingAccessoriesApp Application entry and top-level composition App
SpatialController View lifecycle, callbacks, and feature coordination Concrete collaborators/imported frameworks
AccessoryTrackingModel Feature data or observable state Concrete collaborators/imported frameworks
ThrowSpeedTracker Owns tracking state and updates Concrete collaborators/imported frameworks
AccessoryTrackingView User-interface presentation and input forwarding View
AppStateView User-interface presentation and input forwarding View
GameStateView User-interface presentation and input forwarding View
Throw Represents a feature value or composable behavior Equatable
Shake Represents a feature value or composable behavior Equatable
Direction Defines a closed set of feature states or choices Concrete collaborators/imported frameworks

No local protocol conformance is claimed as protocol-oriented design; external framework conformances are listed only as dependencies.

Access control

Symbol Access Verified effect Likely rationale
verticalSpacing (TrackingAccessories/Entities/CanStack.swift:10) 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.
horizontalSpacing (TrackingAccessories/Entities/CanStack.swift:11) 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.
cans (TrackingAccessories/Entities/CanStack.swift:15) private(set) Read access follows the declaration; writes remain in the private scope. Inference: allow observation while reserving invariant-changing writes for the owner.
toppledCans (TrackingAccessories/Models/AccessoryTrackingModel.swift:35) 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.

Reference code

TrackingAccessories/Entities/CanStack.swift:10 — representative boundary

private let verticalSpacing: Float = 0.18

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 TrackingAccessoriesApp The source’s App suffix makes this role explicit.
View lifecycle, callbacks, and feature coordination SpatialController The source’s Controller suffix makes this role explicit.
Feature data or observable state AccessoryTrackingModel The source’s Model suffix makes this role explicit.
Owns tracking state and updates ThrowSpeedTracker The source’s Tracker suffix makes this role explicit.
User-interface presentation and input forwarding AccessoryTrackingView, AppStateView, GameStateView The source’s View suffix makes this role explicit.

Design patterns

Pattern Source evidence Purpose or tradeoff
View-controller organization TrackingAccessories/Models/SpatialController.swift:12 A controller is the verified coordination boundary; this is MVC-style only where a separate model is present.

Main application flow

Reference code

TrackingAccessories/Models/AccessoryTrackingModel.swift:268trackAllConnectedSpatialControllers()

    private func trackAllConnectedSpatialControllers() {
        // ...
        Task {
            guard state != .accessoryTrackingNotAuthorized && state != .accessoryTrackingNotSupported else {
                print("Can't run ARKit session: \(state)")
                return
            }
            var accessories: [Accessory] = []
            for spatialController in GCController.spatialControllers() {
                do {
                    let accessory = try await Accessory(device: spatialController)
                    accessories.append(accessory)
                } catch {
                    print("Error during accessory initialization: \(error)")
                }
            }
            guard !accessories.isEmpty else {
                state = .noControllerConnected
                arkitSession.stop()
                return
            }
            let accessoryTracking = AccessoryTrackingProvider(accessories: accessories)
            do {
                try await arkitSession.run([accessoryTracking])
                state = .inGame
                gameState = .startNewGame
            } catch {
                return
            }
            for await update in accessoryTracking.anchorUpdates {
                process(update)
            }
        }
    }

Naming conventions

  • Types: App: TrackingAccessoriesApp; Controller: SpatialController; Model: AccessoryTrackingModel; Tracker: ThrowSpeedTracker; View: AccessoryTrackingView, AppStateView, GameStateView.
  • Protocols: no local protocol declaration in the scanned source.
  • Methods: ballThrown, setCanIsToppled, stopTracking, controller, actOnThrow, actOnShake, trackAllConnectedSpatialControllers, process.
  • Files: TrackingAccessories/TrackingAccessoriesApp.swift, TrackingAccessories/Models/SpatialController.swift, TrackingAccessories/Models/AccessoryTrackingModel.swift, TrackingAccessories/Models/ThrowSpeedTracker.swift, TrackingAccessories/Views/AccessoryTrackingView.swift, TrackingAccessories/Views/AppStateView.swift.

Architecture takeaways

  • TrackingAccessoriesApp is the main source-visible entry or composition anchor for this sample.
  • Framework work reaches RealityKit, ARKit, SwiftUI, GameController 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.
  • The source does not justify labeling the design protocol-oriented.

Source map

Source file Relevant symbols
TrackingAccessories/TrackingAccessoriesApp.swift Cited implementation, TrackingAccessoriesApp, SwiftUI
TrackingAccessories/Models/SpatialController.swift Cited implementation, SpatialController, Throw, Shake, Direction
TrackingAccessories/Entities/CanStack.swift Cited implementation, CanStack
TrackingAccessories/Models/AccessoryTrackingModel.swift Cited implementation, Task closure isolated to MainActor, Task, await suspension point, @Observable, NotificationCenter, ARKit, GameController, AccessoryTrackingModel, GameState, State
TrackingAccessories/Entities/Arrow3D.swift @MainActor, RealityKit, Arrow3D
TrackingAccessories/Views/AccessoryTrackingView.swift SwiftUI state property wrapper, AccessoryTrackingView, Attachments
TrackingAccessories/Models/ThrowSpeedTracker.swift Observation, ThrowSpeedTracker
TrackingAccessories/Views/AppStateView.swift AppStateView
TrackingAccessories/Views/GameStateView.swift GameStateView
TrackingAccessories/Entities/Ball.swift Ball
TrackingAccessories/Entities/Can.swift Can
TrackingAccessories/Entities/Crate.swift Crate
TrackingAccessories/Utilities.swift func