swift-conventions
Swift language conventions for any Swift codebase: Swift 6 language mode, value types first, optionals without force-unwraps, error handling (throws, typed throws, Result), protocols and generics (som
SKILL.mdplugins/swift-foundation/skills/swift-conventions/SKILL.md
GitHubSwift Conventions
Know the language mode first
Read it before writing a line — it decides what compiles:
- SwiftPM:
// swift-tools-version:on the first line ofPackage.swift, andswiftLanguageModes:/ per-target.swiftLanguageMode(.v5)settings. Tools version 6.0+ defaults to the Swift 6 language mode. - Xcode:
SWIFT_VERSIONin the target's build settings (project.pbxproj,.xcconfig, Tuist/XcodeGen manifests). - Concurrency settings:
SWIFT_STRICT_CONCURRENCY(minimal / targeted / complete) in Swift 5 mode;SWIFT_DEFAULT_ACTOR_ISOLATION = MainActorandSWIFT_APPROACHABLE_CONCURRENCY = YES(Xcode 26+ app templates turn both on);.defaultIsolation(MainActor.self)in a SwiftPM 6.2+ target.
Never change the language mode, strict-concurrency level or default isolation to make your code compile. Fix the code. Never use a feature newer than the toolchain the project pins (.swift-version, swift-tools-version, CI image).
Types
- Value types by default.
structfor data,enumfor closed sets of cases (with associated values),classonly for identity, shared mutable state, or Objective-C / framework subclassing.final classunless designed for inheritance. letovervar; mutate through methods on astruct(mutating) rather than exposing settable properties.- Model states as an
enuminstead of a cluster of optionals and booleans:
enum LoadState<Value> {
case idle
case loading
case loaded(Value)
case failed(any Error)
}
switchover your own enums exhaustively — nodefault:that would silently swallow a new case. For framework enums marked non-frozen, use@unknown default:.- Prefer
Codablestructs withCodingKeys(or aJSONDecoder.keyDecodingStrategythe project already uses) over hand-written dictionary parsing.
Optionals
- No force unwrap (
!),try!oras!in production code. Allowed:IBOutlets in legacy UIKit, and a compile-time-known literal such asURL(string: "https://example.com")!— nothing derived from input. guard let x else { return / throw }for early exits;if let xfor the happy branch;??for a real default, not to hide a bug.- Never use
fatalError/preconditionfor conditions caused by input, network or disk — throw instead.
Errors
throwsfor recoverable failures. Define domain errors asenum MyError: Errorwith associated values; conform toLocalizedErroronly where a message reaches the user.- Typed throws (
throws(ParseError)) only for small, closed, internal APIs where the caller must handle every case — public APIs and anything that calls into other throwing code stay untyped. Resultis for storing or passing an outcome (callbacks, state), not for returning fromasyncfunctions — useasync throws.- Never
try?an operation whose failure matters; at least log it with context.
Protocols and generics
- Small protocols describing a capability (
protocol UserRepository { func user(id: User.ID) async throws -> User }) — the seam for tests and for swapping implementations. some Protocolfor parameters and return types when one concrete type flows through;any Protocolonly when you need heterogeneous storage. Writeanyexplicitly — it is required in Swift 6 for existential use.- Prefer protocol extensions and generic functions over class hierarchies.
- Do not add a protocol with a single implementation and no test double — that is indirection, not design.
Concurrency
async/awaitfor every asynchronous API you write. No new completion-handler APIs; wrap legacy callbacks once withwithCheckedThrowingContinuationand resume exactly once on every path.- Structured concurrency first:
async letfor a fixed number of parallel calls,withThrowingTaskGroupfor a dynamic number. UnstructuredTask { }only at a boundary (a UI event, a lifecycle hook) — and keep the handle if the work must be cancellable.Task.detachedalmost never. - Respect cancellation in long loops:
try Task.checkCancellation(). - Isolation:
- UI state and anything touching UIKit / AppKit / SwiftUI is
@MainActor. - Shared mutable state that is not UI goes in an
actor. Remember actor reentrancy: re-check state after everyawaitinside an actor method. - Types that cross isolation domains are
Sendable— immutable structs/enums get it for free; classes needfinal+ immutable stored properties, or must be an actor. nonisolatedfor pure functions on isolated types. With approachable concurrency,nonisolated asyncfunctions run on the caller's actor; mark a function@concurrentwhen it must run off the caller's actor (CPU-heavy work).
- UI state and anything touching UIKit / AppKit / SwiftUI is
@unchecked Sendable,nonisolated(unsafe)and@preconcurrency importare escape hatches for code you cannot change (old SDKs, C libraries). Each one needs a comment stating why it is safe. Never use them to silence a warning in code you own.- No
DispatchQueue/DispatchSemaphorein new code unless you are bridging to an API that requires it. Never block a concurrency thread with a semaphore waiting on async work.
Memory
- Closures stored by
self(callbacks,NotificationCenterobservers, Combinesink) capture[weak self]andguard let self else { return }.unownedonly when the lifetime relationship is guaranteed and documented. Task { }started from an object capturesselfstrongly until it finishes; cancel long-running tasks indeinitor the view's.tasklifecycle.- Delegates are
weak var delegate: (any SomeDelegate)?with a class-constrained protocol (AnyObject).
Access control and layout
- Default to
internal;privatefor helpers;public/packageonly for API another module consumes.openonly when subclassing from outside is intended. - One primary type per file, file named after it. Group protocol conformances in
extension Type: Protocol { }blocks. // MARK: -sections only where the file already uses them.
API Design Guidelines (naming)
- Clarity at the point of use:
remove(at: index),user(withID:), notremoveElement(index:). - Types and protocols
UpperCamelCase; everything elselowerCamelCase; acronyms uniform case (userID,urlString,HTTPClient). - Boolean properties read as assertions:
isEmpty,hasChanges,canSubmit. - Mutating/non-mutating pairs:
sort()/sorted(),formUnion()/union(). - Factory methods start with
make. Protocols describing a capability end in-able/-ing; protocols describing what something is are nouns. - Document public API with
///doc comments (summary line,- Parameter,- Returns,- Throws).
Logging
Loggerfromos(Apple platforms) orswift-log(Logger(label:), servers / cross-platform) — whichever the project uses. Noprintin production paths.- Never log tokens, passwords or personal data. With
os.Logger, dynamic values are private by default in release logs — keep it that way; markprivacy: .publiconly for non-sensitive values.