|
| 1 | +# Spacecraft Swift Guidelines — Full Reference |
| 2 | + |
| 3 | +**Version:** 1.0 |
| 4 | +**Date:** 2026-07-12 |
| 5 | +**Author:** Mohamed Hammad & Spacecraft Software |
| 6 | +**Compatibility:** Claude 3.5+, Claude 4, Grok, and all advanced reasoning models |
| 7 | + |
| 8 | +This document expands on the `SKILL.md` for Swift 6.2+ systems programming. It provides complete, compile-checked configurations and skeletons for background execution offloading, SwiftUI ViewModel isolation, Swift Testing with zipped arguments, and optional safety checks. |
| 9 | + |
| 10 | +--- |
| 11 | + |
| 12 | +## 1. Swift 6.2 `@concurrent` Background Execution (SE-0461) |
| 13 | + |
| 14 | +Swift 6.2 defaults to staying on the caller's actor for nonisolated async functions. To run computations in the background, explicitly annotate functions with `@concurrent` to hop to the cooperative concurrent pool. |
| 15 | + |
| 16 | +```swift |
| 17 | +import Foundation |
| 18 | + |
| 19 | +public struct TelemetryPacket: Sendable, Codable { |
| 20 | + public let id: UUID |
| 21 | + public let value: Double |
| 22 | + public let timestamp: Date |
| 23 | +} |
| 24 | + |
| 25 | +/// A service to process telemetry. |
| 26 | +public actor TelemetryProcessor { |
| 27 | + private var processedPackets: [TelemetryPacket] = [] |
| 28 | + |
| 29 | + public init() {} |
| 30 | + |
| 31 | + /// Main entry point isolated to actor. |
| 32 | + public func processPackets(_ rawData: [Data]) async throws { |
| 33 | + // Explicitly offload data parsing to a background concurrent task. |
| 34 | + let parsed = try await parseTelemetryConcurrent(rawData) |
| 35 | + self.processedPackets.append(contentsOf: parsed) |
| 36 | + } |
| 37 | + |
| 38 | + /// Explicitly offloaded background parsing function. |
| 39 | + /// Runs on the global concurrent threadpool via the @concurrent pragma. |
| 40 | + @concurrent |
| 41 | + private func parseTelemetryConcurrent(_ data: [Data]) async throws -> [TelemetryPacket] { |
| 42 | + try await withThrowingTaskGroup(of: TelemetryPacket.self) { group in |
| 43 | + for rawBytes in data { |
| 44 | + group.addTask { |
| 45 | + // Check task cancellation before parsing |
| 46 | + try Task.checkCancellation() |
| 47 | + let decoder = JSONDecoder() |
| 48 | + decoder.dateDecodingStrategy = .iso8601 |
| 49 | + return try decoder.decode(TelemetryPacket.self, from: rawBytes) |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + var results: [TelemetryPacket] = [] |
| 54 | + for try await packet in group { |
| 55 | + results.append(packet) |
| 56 | + } |
| 57 | + return results |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +--- |
| 64 | + |
| 65 | +## 2. MainActor ViewModel & SwiftUI Isolation |
| 66 | + |
| 67 | +Isolate SwiftUI state updates to the `@MainActor`. Offload heavy I/O tasks to background contexts to prevent UI thread starvation. |
| 68 | + |
| 69 | +```swift |
| 70 | +import SwiftUI |
| 71 | + |
| 72 | +@MainActor |
| 73 | +public final class TelemetryViewModel: ObservableObject { |
| 74 | + @Published public private(set) var packets: [TelemetryPacket] = [] |
| 75 | + @Published public private(set) var isLoading = false |
| 76 | + @Published public var errorMessage: String? |
| 77 | + |
| 78 | + private let processor = TelemetryProcessor() |
| 79 | + |
| 80 | + public init() {} |
| 81 | + |
| 82 | + public func loadPackets(from urls: [URL]) async { |
| 83 | + self.isLoading = true |
| 84 | + self.errorMessage = nil |
| 85 | + |
| 86 | + defer { self.isLoading = false } |
| 87 | + |
| 88 | + do { |
| 89 | + var rawData: [Data] = [] |
| 90 | + // Network fetching is non-blocking async |
| 91 | + for url in urls { |
| 92 | + let (data, _) = try await URLSession.shared.data(from: url) |
| 93 | + rawData.append(data) |
| 94 | + } |
| 95 | + |
| 96 | + // Processing occurs on background actor, then hops back to MainActor |
| 97 | + try await processor.processPackets(rawData) |
| 98 | + } catch { |
| 99 | + self.errorMessage = error.localizedDescription |
| 100 | + } |
| 101 | + } |
| 102 | +} |
| 103 | + |
| 104 | +struct TelemetryView: View { |
| 105 | + @StateObject private var viewModel = TelemetryViewModel() |
| 106 | + |
| 107 | + var body: some View { |
| 108 | + NavigationStack { |
| 109 | + List(viewModel.packets, id: \.id) { packet in |
| 110 | + HStack { |
| 111 | + Text(packet.id.uuidString.prefix(8)) |
| 112 | + Spacer() |
| 113 | + Text(String(format: "%.2f", packet.value)) |
| 114 | + } |
| 115 | + } |
| 116 | + .navigationTitle("Telemetry Log") |
| 117 | + .overlay { |
| 118 | + if viewModel.isLoading { |
| 119 | + ProgressView() |
| 120 | + } |
| 121 | + } |
| 122 | + .task { |
| 123 | + let mockURLs = [URL(string: "https://api.spacecraft.org/t1")!] |
| 124 | + await viewModel.loadPackets(from: mockURLs) |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | +} |
| 129 | +``` |
| 130 | + |
| 131 | +--- |
| 132 | + |
| 133 | +## 3. Zipped Parameterized Swift Testing (SE-0470) |
| 134 | + |
| 135 | +Use the Swift Testing framework for testing. Parameterize tests using `arguments` tuples. Use `zip()` to align inputs rather than performing combinations. |
| 136 | + |
| 137 | +```swift |
| 138 | +// Tests/TelemetryTests.swift |
| 139 | +import Testing |
| 140 | +import Foundation |
| 141 | +@testable import TelemetryService |
| 142 | + |
| 143 | +@Suite("Telemetry Service Tests") |
| 144 | +struct TelemetryTests { |
| 145 | + |
| 146 | + // Zipped parameterized test case |
| 147 | + @Test("Validate Parsing Outputs", arguments: zip( |
| 148 | + [ |
| 149 | + "{\"id\":\"00000000-0000-0000-0000-000000000000\",\"value\":42.5,\"timestamp\":\"2026-07-12T20:00:00Z\"}", |
| 150 | + "{\"id\":\"11111111-1111-1111-1111-111111111111\",\"value\":-10.0,\"timestamp\":\"2026-07-12T21:00:00Z\"}" |
| 151 | + ], |
| 152 | + [42.5, -10.0] |
| 153 | + )) |
| 154 | + func testParsing(jsonString: String, expectedValue: Double) throws { |
| 155 | + guard let data = jsonString.data(using: .utf8) else { |
| 156 | + Issue.record("Failed to convert mock json to UTF8 data") |
| 157 | + return |
| 158 | + } |
| 159 | + |
| 160 | + let decoder = JSONDecoder() |
| 161 | + decoder.dateDecodingStrategy = .iso8601 |
| 162 | + |
| 163 | + let packet = try decoder.decode(TelemetryPacket.self, from: data) |
| 164 | + |
| 165 | + #expect(packet.value == expectedValue) |
| 166 | + #expect(packet.timestamp != nil) |
| 167 | + } |
| 168 | + |
| 169 | + @Test("Assert invalid JSON throws error") |
| 170 | + func testParsingFailure() { |
| 171 | + let invalidData = "invalid-json-data".data(using: .utf8)! |
| 172 | + let decoder = JSONDecoder() |
| 173 | + |
| 174 | + #expect(throws: DecodingError.self) { |
| 175 | + try decoder.decode(TelemetryPacket.self, from: invalidData) |
| 176 | + } |
| 177 | + } |
| 178 | +} |
| 179 | +``` |
| 180 | + |
| 181 | +--- |
| 182 | + |
| 183 | +## 4. Retain Cycles & ARC Memory Hygiene |
| 184 | + |
| 185 | +To prevent leaks in async closures, use weak capturing. Avoid force-unwraps (`!`) to prevent runtime crashes. |
| 186 | + |
| 187 | +```swift |
| 188 | +import Foundation |
| 189 | + |
| 190 | +public final class DeviceMonitor { |
| 191 | + private var updateHandler: ((Double) -> Void)? |
| 192 | + private var lastValue: Double = 0.0 |
| 193 | + |
| 194 | + public init() {} |
| 195 | + |
| 196 | + public func configureHandler() { |
| 197 | + // Use weak self to prevent retain cycles |
| 198 | + self.updateHandler = { [weak self] val in |
| 199 | + guard let self = self else { return } |
| 200 | + self.lastValue = val |
| 201 | + print("Received value: \(val)") |
| 202 | + } |
| 203 | + } |
| 204 | + |
| 205 | + public func processSample(value: Double?) { |
| 206 | + // Safe unwrapping instead of force-unwrapping (value!) |
| 207 | + guard let unwrappedValue = value else { |
| 208 | + print("Received null telemetry reading") |
| 209 | + return |
| 210 | + } |
| 211 | + self.updateHandler?(unwrappedValue) |
| 212 | + } |
| 213 | +} |
| 214 | +``` |
| 215 | + |
| 216 | +--- |
| 217 | + |
| 218 | +## 5. Swift Package Manager Configuration (`Package.swift`) |
| 219 | + |
| 220 | +Configure strict concurrency checking and warnings as errors in `Package.swift`. |
| 221 | + |
| 222 | +```swift |
| 223 | +// swift-tools-version: 6.2 |
| 224 | +import PackageDescription |
| 225 | + |
| 226 | +let package = Package( |
| 227 | + name: "TelemetryService", |
| 228 | + platforms: [ |
| 229 | + .iOS(.v17), |
| 230 | + .macOS(.v14) |
| 231 | + ], |
| 232 | + products: [ |
| 233 | + .library(name: "TelemetryService", targets: ["TelemetryService"]) |
| 234 | + ], |
| 235 | + dependencies: [], |
| 236 | + targets: [ |
| 237 | + .target( |
| 238 | + name: "TelemetryService", |
| 239 | + dependencies: [], |
| 240 | + swiftSettings: [ |
| 241 | + // Enforce strict concurrency checks (warnings treated as errors in Swift 6) |
| 242 | + .enableUpcomingFeature("StrictConcurrency"), |
| 243 | + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), |
| 244 | + .enableUpcomingFeature("InferIsolatedConformances"), |
| 245 | + .unsafeFlags(["-warnings-as-errors"]) |
| 246 | + ] |
| 247 | + ), |
| 248 | + .testTarget( |
| 249 | + name: "TelemetryServiceTests", |
| 250 | + dependencies: ["TelemetryService"], |
| 251 | + swiftSettings: [ |
| 252 | + .enableUpcomingFeature("StrictConcurrency"), |
| 253 | + .unsafeFlags(["-warnings-as-errors"]) |
| 254 | + ] |
| 255 | + ) |
| 256 | + ] |
| 257 | +) |
| 258 | +``` |
| 259 | + |
| 260 | +--- |
| 261 | + |
| 262 | +## 6. Common Pitfalls & Troubleshooting |
| 263 | + |
| 264 | +| Pitfall | Symptom | Corrective Action | |
| 265 | +| :--- | :--- | :--- | |
| 266 | +| **Force-unwrapping (`!`) optionals** | Thread crashes with fatal error | Use `guard let` or provide defaults using `??`. | |
| 267 | +| **Retain cycles in async closures** | Memory leaks (objects are never released) | Capture references weakly: `[weak self]`. | |
| 268 | +| **MainActor blockages** | SwiftUI interfaces freeze or frame drops | Annotate heavy functions with `@concurrent` or process on a separate background `actor`. | |
| 269 | +| **Unchecked Sendable escapes** | Undefined thread data races | Avoid `@unchecked Sendable`. Use locks only if wrapping FFI structures, verified under Thread Sanitizer. | |
| 270 | +| **Cartesian parameterized tests** | Tests run too many combinations | Use `zip()` inside `@Test(arguments: zip(...))` to align arguments. | |
| 271 | + |
| 272 | +--- |
| 273 | + |
| 274 | +## 7. Code Review Compliance Gate |
| 275 | + |
| 276 | +Before merging Swift code, verify: |
| 277 | +1. Compilation passes with strict concurrency checks and `-warnings-as-errors` active. |
| 278 | +2. No force-unwraps (`!`) or force-casts (`as!`) exist in any production path. |
| 279 | +3. Every asynchronous closure capturing `self` uses the `[weak self]` capture list. |
| 280 | +4. ViewModels update state variables on the `@MainActor`. |
| 281 | +5. Unit tests run on the modern `Testing` framework (not `XCTest`). |
0 commit comments