Write idiomatic Swift
Swift is safest when values are structs, absence is an optional you handle, and
concurrency is checked by the compiler through actors and Sendable. For the builder and the reviewer of a Swift diff; the target's settings and existing code win over it.
Procedure
- Discover the target's conventions first. Call
search_lore for Swift conventions.
Read Package.swift (swift-tools-version, swiftLanguageModes, swiftSettings
such as upcoming features or defaultIsolation(MainActor.self)), or the Xcode build
settings (SWIFT_VERSION, SWIFT_STRICT_CONCURRENCY, SWIFT_DEFAULT_ACTOR_ISOLATION,
approachable-concurrency flags), project.yml (XcodeGen/Tuist), .swiftlint.yml,
.swift-format, and the minimum OS. The language mode decides the rules: in Swift 6
mode data-race diagnostics are errors; with default MainActor isolation (6.2) code is
main-actor unless marked otherwise. Identify SwiftUI vs UIKit, the architecture
(@Observable MVVM, TCA), and XCTest vs Swift Testing. Copy a sibling feature and test.
- Pin the exact commands from CI,
Makefile or fastlane (the run-tests and
run-lint skills), including the scheme and simulator destination. Use the defaults
below only when the repo defines none.
- Write the change with the idioms below, then walk the concurrency section for every
task, actor, closure, file and shared object you touched.
- Test each acceptance criterion's own behaviour. One test per AC that fails without
your change, plus its error path (
@Test(arguments:) for tables). If the AC involves
shared state or persistence, add a test that runs N concurrent calls in a
withTaskGroup and asserts the invariant.
- Verify, then stop. Done when: the build has no new warnings in the configured
language mode, SwiftLint/swift-format are clean, tests are green on the repo's
destination, and every AC has a test. Record the output with the
record-evidence
skill; the runner submits the work.
Commands
- SwiftPM:
swift build and swift test (one test: swift test --filter Suite/test).
Never swift package update or edit Package.resolved; a new or bumped package is a
blocker: mark_ticket_blocked with the exact command a human should run.
- Xcode:
xcodebuild -list, then xcodebuild test -scheme <Scheme> -destination '<CI destination>'.
- Lint:
swiftlint lint --strict (if configured); swift format lint --strict --recursive Sources Tests (swift-format ships with the Swift 6 toolchain).
Idioms that matter
- API Design Guidelines: clarity at the point of use; name by role, not type; omit
needless words; argument labels that read as phrases (
insert(_:at:)); mutating/
non-mutating pairs sort()/sorted(); Booleans read as assertions (isEmpty); a
documentation comment on every public declaration; note complexity when a computed
property is not O(1).
- Value types first:
struct/enum for models and state; class only for identity,
and final unless designed for subclassing; protocols with extensions over inheritance.
- Optionals:
guard let with early return, ?? with a real default, optional
chaining. No !, try! or implicitly unwrapped optionals on reachable paths (only
@IBOutlet).
- Errors:
throws with a module error enum (typed throws(MyError) where the repo uses
it), handled at the boundary; try? only where absence is acceptable, with a comment.
- Exhaustive
switch on enums the module owns, with no default.
- SwiftUI: small views; state owned at the right level (
@State local, @Binding
down, @Observable models injected); .task for async work tied to view lifetime; no
side effects in body.
Concurrency and resource safety
- Isolation is the lock. UI state is
@MainActor; shared mutable state lives in an
actor. Sendable conformances are honest: no @unchecked Sendable,
nonisolated(unsafe) or MainActor.assumeIsolated without a written proof.
- Actor reentrancy: an actor method that awaits can be interleaved with other calls on
the same actor, so state read before an
await may be stale after it — a lost update
inside an actor. Re-check invariants after each await, or finish the read-modify-write
synchronously before suspending, or dedupe in-flight work with a stored Task.
- Unstructured tasks (
Task { }, Task.detached) are not cancelled with their creator:
keep the handle and cancel it (in deinit, onDisappear, or by using .task). Prefer
async let and task groups. Long loops call try Task.checkCancellation().
- Offloading work: CPU-heavy or blocking work does not run on the main actor; mark it
@concurrent (6.2) or move it to a non-main actor. Never DispatchQueue.main.sync
from the main thread; never block a task on a semaphore waiting for another task.
- Continuations (
withCheckedThrowingContinuation) resume exactly once on every path.
- Memory:
[weak self] in escaping closures stored by objects that self owns
(timers, observers, publishers); break parent/child reference cycles; defer to release
resources.
- Files other readers use: write with
data.write(to: url, options: .atomic) (temp file
plus rename) or FileManager.replaceItemAt; never a fixed temp name. Cross-process
exclusion needs a file lock or the database; a time-only lease lets a suspended holder
write late, so writes must check a version.
Review checklist — flag as defects
Walk this against the diff. An item is grounds for CHANGES only when, in changed code, it
causes a concrete failure (wrong result, crash, lost or corrupted data, security hole) or
leaves an AC's own behaviour untested: cite the line and that failure. Otherwise it is an
(optional) note. Formatting the tools would fix, and preferences the repo
does not enforce, are not findings. Do not patch the code under review.
Capture lore
This skill is one of the places durable, reusable knowledge naturally surfaces:
While matching the target you learn the architecture pattern, the DI approach and the concurrency conventions the app relies on. That kind of fact is lore. Capture it via the lore-capture
protocol in your brief (CLAUDE.factory.md, step 11 "Memory contribution"):
call the Memory MCP suggest_lore once at the close of your work — reusable
conventions, gotchas, decisions, and boundaries only, never per-ticket trivia.
1---2name: swift-conventions3description: Use when a ticket adds or changes Swift code — iOS/macOS apps, SwiftUI or UIKit, server-side Swift — and it must follow the repo's Swift conventions — the Swift API Design Guidelines, value types and protocols, optionals handled without force-unwraps, Swift 6 strict concurrency (async/await, actors, Sendable) used correctly, SwiftLint/swift-format clean — as the language pack for any Swift change. Invoke for "build this screen in SwiftUI", "fix the retain cycle", "remove the force unwraps", "fix the Sendable/data-race errors", or when reviewing a Swift diff.4stack: [swift, ios, macos]5area: language6metadata:7 source: https://skillmd.com/skills/tmj-90/swift-conventions8---910# Write idiomatic Swift1112Swift is safest when values are structs, absence is an optional you handle, and13concurrency is checked by the compiler through actors and `Sendable`. For the builder and the reviewer of a Swift diff; the target's settings and existing code win over it.1415## Procedure16171. **Discover the target's conventions first.** Call `search_lore` for Swift conventions.18 Read `Package.swift` (`swift-tools-version`, `swiftLanguageModes`, `swiftSettings`19 such as upcoming features or `defaultIsolation(MainActor.self)`), or the Xcode build20 settings (`SWIFT_VERSION`, `SWIFT_STRICT_CONCURRENCY`, `SWIFT_DEFAULT_ACTOR_ISOLATION`,21 approachable-concurrency flags), `project.yml` (XcodeGen/Tuist), `.swiftlint.yml`,22 `.swift-format`, and the minimum OS. The language mode decides the rules: in Swift 623 mode data-race diagnostics are errors; with default MainActor isolation (6.2) code is24 main-actor unless marked otherwise. Identify SwiftUI vs UIKit, the architecture25 (`@Observable` MVVM, TCA), and XCTest vs Swift Testing. Copy a sibling feature and test.262. **Pin the exact commands** from CI, `Makefile` or fastlane (the `run-tests` and27 `run-lint` skills), including the scheme and simulator destination. Use the defaults28 below only when the repo defines none.293. **Write the change with the idioms below**, then walk the concurrency section for every30 task, actor, closure, file and shared object you touched.314. **Test each acceptance criterion's own behaviour.** One test per AC that fails without32 your change, plus its error path (`@Test(arguments:)` for tables). If the AC involves33 shared state or persistence, add a test that runs N concurrent calls in a34 `withTaskGroup` and asserts the invariant.355. **Verify, then stop.** Done when: the build has no new warnings in the configured36 language mode, SwiftLint/swift-format are clean, tests are green on the repo's37 destination, and every AC has a test. Record the output with the `record-evidence`38 skill; the runner submits the work.3940## Commands4142- SwiftPM: `swift build` and `swift test` (one test: `swift test --filter Suite/test`).43 Never `swift package update` or edit `Package.resolved`; a new or bumped package is a44 blocker: `mark_ticket_blocked` with the exact command a human should run.45- Xcode: `xcodebuild -list`, then `xcodebuild test -scheme <Scheme> -destination46 '<CI destination>'`.47- Lint: `swiftlint lint --strict` (if configured); `swift format lint --strict48 --recursive Sources Tests` (swift-format ships with the Swift 6 toolchain).4950## Idioms that matter5152- **API Design Guidelines**: clarity at the point of use; name by role, not type; omit53 needless words; argument labels that read as phrases (`insert(_:at:)`); mutating/54 non-mutating pairs `sort()`/`sorted()`; Booleans read as assertions (`isEmpty`); a55 documentation comment on every public declaration; note complexity when a computed56 property is not O(1).57- **Value types first**: `struct`/`enum` for models and state; `class` only for identity,58 and `final` unless designed for subclassing; protocols with extensions over inheritance.59- **Optionals**: `guard let` with early return, `??` with a real default, optional60 chaining. No `!`, `try!` or implicitly unwrapped optionals on reachable paths (only61 `@IBOutlet`).62- **Errors**: `throws` with a module error enum (typed `throws(MyError)` where the repo uses63 it), handled at the boundary; `try?` only where absence is acceptable, with a comment.64- **Exhaustive `switch`** on enums the module owns, with no `default`.65- **SwiftUI**: small views; state owned at the right level (`@State` local, `@Binding`66 down, `@Observable` models injected); `.task` for async work tied to view lifetime; no67 side effects in `body`.6869## Concurrency and resource safety7071- **Isolation is the lock.** UI state is `@MainActor`; shared mutable state lives in an72 `actor`. `Sendable` conformances are honest: no `@unchecked Sendable`,73 `nonisolated(unsafe)` or `MainActor.assumeIsolated` without a written proof.74- **Actor reentrancy**: an actor method that awaits can be interleaved with other calls on75 the same actor, so state read before an `await` may be stale after it — a lost update76 inside an actor. Re-check invariants after each `await`, or finish the read-modify-write77 synchronously before suspending, or dedupe in-flight work with a stored `Task`.78- **Unstructured tasks** (`Task { }`, `Task.detached`) are not cancelled with their creator:79 keep the handle and cancel it (in `deinit`, `onDisappear`, or by using `.task`). Prefer80 `async let` and task groups. Long loops call `try Task.checkCancellation()`.81- **Offloading work**: CPU-heavy or blocking work does not run on the main actor; mark it82 `@concurrent` (6.2) or move it to a non-main actor. Never `DispatchQueue.main.sync`83 from the main thread; never block a task on a semaphore waiting for another task.84- **Continuations** (`withCheckedThrowingContinuation`) resume exactly once on every path.85- **Memory**: `[weak self]` in escaping closures stored by objects that `self` owns86 (timers, observers, publishers); break parent/child reference cycles; `defer` to release87 resources.88- **Files other readers use**: write with `data.write(to: url, options: .atomic)` (temp file89 plus rename) or `FileManager.replaceItemAt`; never a fixed temp name. Cross-process90 exclusion needs a file lock or the database; a time-only lease lets a suspended holder91 write late, so writes must check a version.9293## Review checklist — flag as defects9495Walk this against the diff. An item is grounds for CHANGES only when, in changed code, it96causes a concrete failure (wrong result, crash, lost or corrupted data, security hole) or97leaves an AC's own behaviour untested: cite the line and that failure. Otherwise it is an98`(optional)` note. Formatting the tools would fix, and preferences the repo99does not enforce, are not findings. Do not patch the code under review.100101- [ ] `!`, `try!` or an implicitly unwrapped optional on a reachable path; `try?` silently102 discarding an error the caller needed.103- [ ] `@unchecked Sendable`, `nonisolated(unsafe)` or a lowered strict-concurrency setting104 without a proof; UI state mutated off the main actor.105- [ ] Actor state read before an `await` and written after it without re-checking.106- [ ] An unstructured `Task` never cancelled; missing cancellation checks in long work.107- [ ] Blocking or heavy work on the main actor; `DispatchQueue.main.sync` or a semaphore108 wait inside async code; a continuation resumed zero or two times.109- [ ] A reference cycle through an escaping closure or delegate held strongly.110- [ ] A shared file written in place or via a fixed temp name; a time-only lock lease.111- [ ] `default` on a `switch` over an enum the module owns, hiding a future case.112- [ ] A new SwiftLint `disable` without a reason.113- [ ] An AC has no test, or an async test waits with sleeps instead of awaiting or114 `confirmation`/expectations.115116## Capture lore117118This skill is one of the places durable, reusable knowledge naturally surfaces:119**While matching the target you learn the architecture pattern, the DI approach and the concurrency conventions the app relies on.** That kind of fact is *lore*. Capture it via the **lore-capture120protocol in your brief** (`CLAUDE.factory.md`, step 11 "Memory contribution"):121call the Memory MCP `suggest_lore` once at the close of your work — reusable122conventions, gotchas, decisions, and boundaries only, never per-ticket trivia.