Swift Idioms and Patterns
Swift rewards value types, optionals, and protocol-oriented design. Idiomatic Swift = safe, expressive, Swifty.
Scope: Swift coding idioms. Test naming: .agents/rules/testing-strategy.md.
Value Types and Optionals
Prefer structs over classes — value semantics by default. Classes only for identity, inheritance, or reference counting.
Optionals — never force-unwrap (!) in production:
// ✅ Guard let for early exit
guard let task = storage.findById(id) else {
throw TaskError.notFound(id)
}
// ✅ Optional chaining
let title = task?.title ?? "Untitled"
// ✅ if let for conditional binding
if let deadline = task.deadline {
scheduleReminder(for: deadline)
}
// ❌ Force unwrap — crash risk
let task = storage.findById(id)!
Property wrappers for reusable behavior:
@propertyWrapper
struct Clamped<Value: Comparable> {
var wrappedValue: Value {
didSet { wrappedValue = min(max(wrappedValue, range.lowerBound), range.upperBound) }
}
let range: ClosedRange<Value>
init(wrappedValue: Value, _ range: ClosedRange<Value>) {
self.range = range
self.wrappedValue = min(max(wrappedValue, range.lowerBound), range.upperBound)
}
}
struct Task {
@Clamped(0...100) var progress: Int = 0
}
Error Handling
For universal error handling principles, see .agents/rules/error-handling-principles.md.
Typed throws (Swift 6) or Error protocol:
enum TaskError: Error, LocalizedError {
case notFound(String)
case validationFailed(field: String, message: String)
case storageUnavailable
var errorDescription: String? {
switch self {
case .notFound(let id): "Task '\(id)' not found"
case .validationFailed(let field, let msg): "Validation failed on \(field): \(msg)"
case .storageUnavailable: "Storage is unavailable"
}
}
}
func getTask(id: String) throws(TaskError) -> Task { ... }
Result type for async callbacks (pre-async/await):
func fetchTask(id: String) async -> Result<Task, TaskError> { ... }
do/catch with pattern matching:
do {
let task = try getTask(id: "123")
process(task)
} catch TaskError.notFound(let id) {
logger.warn("Task not found", metadata: ["taskId": id])
} catch {
logger.error("Unexpected error", metadata: ["error": "\(error)"])
}
defer for cleanup:
func processFile(at path: String) throws -> Data {
let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path))
defer { handle.closeFile() } // ✅ Always runs on exit
return handle.readDataToEndOfFile()
}
Protocol-Oriented Design
Protocols over abstract classes:
// ✅ Interface defined as protocol
protocol TaskStorage {
func getById(_ id: String) async throws -> Task?
func save(_ task: Task) async throws
}
// ✅ Production implementation
struct PostgresTaskStorage: TaskStorage {
let pool: ConnectionPool
func getById(_ id: String) async throws -> Task? {
try await pool.query("SELECT * FROM tasks WHERE id = $1", [id]).first
}
func save(_ task: Task) async throws {
try await pool.execute("INSERT INTO tasks ...", [task.id, task.title])
}
}
// ✅ Test implementation
struct MockTaskStorage: TaskStorage {
var tasks: [Task] = []
func getById(_ id: String) async throws -> Task? {
tasks.first { $0.id == id }
}
func save(_ task: Task) async throws {
tasks.append(task)
}
}
Protocol extensions for default implementations:
protocol Identifiable {
var id: String { get }
}
extension Identifiable {
var isNew: Bool { id.isEmpty }
}
Associated types for generic protocols:
protocol Repository {
associatedtype Entity
func findById(_ id: String) async throws -> Entity?
func save(_ entity: Entity) async throws
}
Concurrency
Structured concurrency with async/await:
func loadDashboard() async throws -> Dashboard {
async let user = fetchUser(id)
async let tasks = fetchTasks(userId: id)
async let stats = fetchStats()
return Dashboard(
user: try await user,
tasks: try await tasks,
stats: try await stats
)
}
@Sendable for closures crossing concurrency domains.
Actors for thread-safe mutable state:
actor TaskCache {
private var cache: [String: Task] = [:]
func get(_ id: String) -> Task? { cache[id] }
func set(_ id: String, task: Task) { cache[id] = task }
func invalidate(_ id: String) { cache.removeValue(forKey: id) }
}
// ✅ Safe concurrent access
let cache = TaskCache()
await cache.set("123", task: newTask)
if let task = await cache.get("123") { ... }
TaskGroup for dynamic concurrency:
func fetchAllTasks(ids: [String]) async throws -> [Task] {
try await withThrowingTaskGroup(of: Task.self) { group in
for id in ids {
group.addTask { try await fetchTask(id: id) }
}
return try await group.reduce(into: []) { $0.append($1) }
}
}
Naming (Swift API Design Guidelines)
- camelCase for functions, properties, variables.
- PascalCase for types, protocols, enums.
- Omit needless words —
remove(at:) not removeItem(atIndex:).
- Protocols for capabilities use
-able/-ible: Codable, Identifiable.
- Factory methods use
make prefix: makeIterator().
- Boolean properties read as assertions:
isEmpty, hasChanges, isValid.
Anti-Patterns
- ❌ Force unwrap (
!) in production code — crashes at runtime
- ❌
var when let suffices — always prefer immutability
- ❌ Classes when structs work — unnecessary reference semantics
- ❌ Stringly-typed APIs — use enums for finite option sets
- ❌ Massive view controllers — extract to view models, coordinators
- ❌
try? silently discarding errors — log or handle the error case
- ❌ Nested
if let pyramids — use guard let for early returns
// ❌ Pyramid of doom
if let user = getUser() {
if let tasks = getTasks(for: user) {
if let first = tasks.first {
process(first)
}
}
}
// ✅ Flat with guard
guard let user = getUser() else { return }
guard let tasks = getTasks(for: user), let first = tasks.first else { return }
process(first)
Testing
XCTest or Swift Testing (6.0+). Mock via protocols.
// XCTest
final class TaskServiceTests: XCTestCase {
func testGetTask_returnsNotFound() async throws {
let storage = MockTaskStorage()
let service = TaskService(storage: storage)
do {
_ = try await service.getTask(id: "999")
XCTFail("Expected notFound error")
} catch TaskError.notFound(let id) {
XCTAssertEqual(id, "999")
}
}
}
// Swift Testing (6.0+)
@Test func getTask_returnsNotFound() async throws {
let storage = MockTaskStorage()
let service = TaskService(storage: storage)
#expect(throws: TaskError.notFound("999")) {
try await service.getTask(id: "999")
}
}
Formatting and Static Analysis
| Tool |
Purpose |
Command |
swift-format |
Formatting |
swift-format -i -r Sources/ |
| SwiftLint |
Linting |
swiftlint lint --strict |
| Xcode Analyzer |
Static analysis |
Built-in |
Related
- Code Idioms and Conventions .agents/rules/code-idioms-and-conventions.md
- Testing Strategy .agents/rules/testing-strategy.md
- Error Handling Principles .agents/rules/error-handling-principles.md
- Concurrency and Threading Principles @.agents/rules/concurrency-and-threading-principles.md
1---2name: swift-idioms-23description: Swift Idioms and Patterns4---56## Swift Idioms and Patterns78Swift rewards value types, optionals, and protocol-oriented design. Idiomatic Swift = safe, expressive, Swifty.910> Scope: Swift coding idioms. Test naming: .agents/rules/testing-strategy.md.1112### Value Types and Optionals13141. **Prefer structs over classes** — value semantics by default. Classes only for identity, inheritance, or reference counting.152. **Optionals — never force-unwrap (`!`) in production:**16 ```swift17 // ✅ Guard let for early exit18 guard let task = storage.findById(id) else {19 throw TaskError.notFound(id)20 }2122 // ✅ Optional chaining23 let title = task?.title ?? "Untitled"2425 // ✅ if let for conditional binding26 if let deadline = task.deadline {27 scheduleReminder(for: deadline)28 }2930 // ❌ Force unwrap — crash risk31 let task = storage.findById(id)!32 ```33343. **Property wrappers** for reusable behavior:35 ```swift36 @propertyWrapper37 struct Clamped<Value: Comparable> {38 var wrappedValue: Value {39 didSet { wrappedValue = min(max(wrappedValue, range.lowerBound), range.upperBound) }40 }41 let range: ClosedRange<Value>4243 init(wrappedValue: Value, _ range: ClosedRange<Value>) {44 self.range = range45 self.wrappedValue = min(max(wrappedValue, range.lowerBound), range.upperBound)46 }47 }4849 struct Task {50 @Clamped(0...100) var progress: Int = 051 }52 ```5354### Error Handling5556> For universal error handling principles, see `.agents/rules/error-handling-principles.md`.57581. **Typed throws (Swift 6) or `Error` protocol:**59 ```swift60 enum TaskError: Error, LocalizedError {61 case notFound(String)62 case validationFailed(field: String, message: String)63 case storageUnavailable6465 var errorDescription: String? {66 switch self {67 case .notFound(let id): "Task '\(id)' not found"68 case .validationFailed(let field, let msg): "Validation failed on \(field): \(msg)"69 case .storageUnavailable: "Storage is unavailable"70 }71 }72 }7374 func getTask(id: String) throws(TaskError) -> Task { ... }75 ```76772. **`Result` type for async callbacks** (pre-async/await):78 ```swift79 func fetchTask(id: String) async -> Result<Task, TaskError> { ... }80 ```81823. **`do`/`catch` with pattern matching:**83 ```swift84 do {85 let task = try getTask(id: "123")86 process(task)87 } catch TaskError.notFound(let id) {88 logger.warn("Task not found", metadata: ["taskId": id])89 } catch {90 logger.error("Unexpected error", metadata: ["error": "\(error)"])91 }92 ```93944. **`defer` for cleanup:**95 ```swift96 func processFile(at path: String) throws -> Data {97 let handle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path))98 defer { handle.closeFile() } // ✅ Always runs on exit99100 return handle.readDataToEndOfFile()101 }102 ```103104### Protocol-Oriented Design1051061. **Protocols over abstract classes:**107 ```swift108 // ✅ Interface defined as protocol109 protocol TaskStorage {110 func getById(_ id: String) async throws -> Task?111 func save(_ task: Task) async throws112 }113114 // ✅ Production implementation115 struct PostgresTaskStorage: TaskStorage {116 let pool: ConnectionPool117118 func getById(_ id: String) async throws -> Task? {119 try await pool.query("SELECT * FROM tasks WHERE id = $1", [id]).first120 }121122 func save(_ task: Task) async throws {123 try await pool.execute("INSERT INTO tasks ...", [task.id, task.title])124 }125 }126127 // ✅ Test implementation128 struct MockTaskStorage: TaskStorage {129 var tasks: [Task] = []130131 func getById(_ id: String) async throws -> Task? {132 tasks.first { $0.id == id }133 }134135 func save(_ task: Task) async throws {136 tasks.append(task)137 }138 }139 ```1401412. **Protocol extensions for default implementations:**142 ```swift143 protocol Identifiable {144 var id: String { get }145 }146147 extension Identifiable {148 var isNew: Bool { id.isEmpty }149 }150 ```1511523. **Associated types for generic protocols:**153 ```swift154 protocol Repository {155 associatedtype Entity156 func findById(_ id: String) async throws -> Entity?157 func save(_ entity: Entity) async throws158 }159 ```160161### Concurrency1621631. **Structured concurrency with `async`/`await`:**164 ```swift165 func loadDashboard() async throws -> Dashboard {166 async let user = fetchUser(id)167 async let tasks = fetchTasks(userId: id)168 async let stats = fetchStats()169170 return Dashboard(171 user: try await user,172 tasks: try await tasks,173 stats: try await stats174 )175 }176 ```1771782. **`@Sendable`** for closures crossing concurrency domains.1793. **Actors** for thread-safe mutable state:180 ```swift181 actor TaskCache {182 private var cache: [String: Task] = [:]183184 func get(_ id: String) -> Task? { cache[id] }185 func set(_ id: String, task: Task) { cache[id] = task }186 func invalidate(_ id: String) { cache.removeValue(forKey: id) }187 }188189 // ✅ Safe concurrent access190 let cache = TaskCache()191 await cache.set("123", task: newTask)192 if let task = await cache.get("123") { ... }193 ```1941954. **`TaskGroup`** for dynamic concurrency:196 ```swift197 func fetchAllTasks(ids: [String]) async throws -> [Task] {198 try await withThrowingTaskGroup(of: Task.self) { group in199 for id in ids {200 group.addTask { try await fetchTask(id: id) }201 }202 return try await group.reduce(into: []) { $0.append($1) }203 }204 }205 ```206207### Naming (Swift API Design Guidelines)2082091. **camelCase** for functions, properties, variables.2102. **PascalCase** for types, protocols, enums.2113. **Omit needless words** — `remove(at:)` not `removeItem(atIndex:)`.2124. **Protocols for capabilities** use `-able`/`-ible`: `Codable`, `Identifiable`.2135. **Factory methods** use `make` prefix: `makeIterator()`.2146. **Boolean properties** read as assertions: `isEmpty`, `hasChanges`, `isValid`.215216### Anti-Patterns217218- ❌ **Force unwrap (`!`) in production code** — crashes at runtime219- ❌ **`var` when `let` suffices** — always prefer immutability220- ❌ **Classes when structs work** — unnecessary reference semantics221- ❌ **Stringly-typed APIs** — use enums for finite option sets222- ❌ **Massive view controllers** — extract to view models, coordinators223- ❌ **`try?` silently discarding errors** — log or handle the error case224- ❌ **Nested `if let` pyramids** — use `guard let` for early returns225226```swift227// ❌ Pyramid of doom228if let user = getUser() {229 if let tasks = getTasks(for: user) {230 if let first = tasks.first {231 process(first)232 }233 }234}235236// ✅ Flat with guard237guard let user = getUser() else { return }238guard let tasks = getTasks(for: user), let first = tasks.first else { return }239process(first)240```241242### Testing243244XCTest or Swift Testing (6.0+). Mock via protocols.245246```swift247// XCTest248final class TaskServiceTests: XCTestCase {249 func testGetTask_returnsNotFound() async throws {250 let storage = MockTaskStorage()251 let service = TaskService(storage: storage)252253 do {254 _ = try await service.getTask(id: "999")255 XCTFail("Expected notFound error")256 } catch TaskError.notFound(let id) {257 XCTAssertEqual(id, "999")258 }259 }260}261262// Swift Testing (6.0+)263@Test func getTask_returnsNotFound() async throws {264 let storage = MockTaskStorage()265 let service = TaskService(storage: storage)266267 #expect(throws: TaskError.notFound("999")) {268 try await service.getTask(id: "999")269 }270}271```272273### Formatting and Static Analysis274275| Tool | Purpose | Command |276|---|---|---|277| `swift-format` | Formatting | `swift-format -i -r Sources/` |278| SwiftLint | Linting | `swiftlint lint --strict` |279| Xcode Analyzer | Static analysis | Built-in |280281### Related282- Code Idioms and Conventions .agents/rules/code-idioms-and-conventions.md283- Testing Strategy .agents/rules/testing-strategy.md284- Error Handling Principles .agents/rules/error-handling-principles.md285- Concurrency and Threading Principles @.agents/rules/concurrency-and-threading-principles.md