/swift:codingfrom swift
Use when writing or reviewing Swift, covering functional design with typed throws, value types, and structured concurrency
Ships in swift. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Code uses each module's types wherever they state a value, and a module below performs its field's job before any hand form:
| [INDEX] | [FIELD] | [MODULES] |
|---|---|---|
| [01] | Language | Standard library, Swift Concurrency, Synchronization, Observation |
| [02] | Collections | OrderedCollections, DequeModule, HeapModule, HashTreeCollections, BitCollections |
| [03] | Async sequences | AsyncAlgorithms |
| [04] | Enum cases | CasePaths declaring @CasePathable, CasePathsCore for code reading paths alone |
| [05] | Files, processes | System, Subprocess |
| [06] | Settings | Configuration |
| [07] | Service lifecycle | ServiceLifecycle, UnixSignals |
| [08] | Observability | Logging, Tracing, Instrumentation, OTel, OTelSemanticConventions |
| [09] | Process metrics | SystemMetrics |
| [10] | App updates | Sparkle |
| [11] | Command lines | ArgumentParser |
[REFERENCES]:
Use swift:testing for suites.
Function types state each effect of a call on the function that performs it:
| [INDEX] | [ANNOTATION] | [STATES] |
|---|---|---|
| [01] | throws(E) | Fails with E, throws(Never) and no annotation never fail |
| [02] | async | Suspends, a nonisolated one runs on its caller's actor |
| [03] | @concurrent | Runs off its caller's actor |
| [04] | @Sendable | Crosses isolation, captures only Sendable values |
| [05] | sending | Moves the value to another isolation region, the sender stops using it |
| [06] | borrowing, consuming | Reads the argument, or takes ownership of it |
allCasesinternal until another module calls them, package within one package, public for a product's APIpublic import or package import names the module declaring a type its signatures state, and members resolve through a module the file importsFunctions are total when every input they accept reaches a declared outcome. Narrow input to a validated type or widen outcome to an Optional or typed throw:
init? constructs a value whose only failure is absence, init(_:) throws(E) constructs one whose failure has a reasonJSONValue drops its malformed reason(T) throws(E) -> U and throwing E themselves (Task.withTimeout(_:expired:clock:_:))throws(E), an unannotated one infers any Error, and one that never throws binds E to Nevermap, filter, count(where:), Optional.map, and Optional.flatMap keep E. Rethrowing members (reduce, compactMap, first(where:), contains(where:), allSatisfy, sorted(by:)) widen E to any Error. Typed steps run through a typed member, and the rethrowing member takes the non-throwing remainder.
Current instant, user locale, host settings, and random source (inout some RandomNumberGenerator) enter as arguments, and a function that waits or measures takes some Clock<Duration>. Boundaries read the host once and pass values: a pure function turns NSEvent.doubleClickInterval and key repeat timing into a replayable event course, with jitter from a seeded generator.
if and switch are expressions when each branch is one expression, and a binding, return, or property takes it whole. Branches needing statements make the if or switch a statement. Closures nest one level, and a decision over a discriminant becomes a tuple switch or a table:
let <name>: <Type> = switch <subject> { ... } binds a value each arm selects, a throw arm stays in placeswitch does the shared work (let (tag, key, error): (String, Key, any Error) = switch self in an encode(to:))count(where:) counts, indices(where:) returns a RangeSet that removeSubranges and the subranges subscript take wholezip(items, items.dropFirst()) reads neighbors, Dictionary(_:uniquingKeysWith: +) counts by key, Dictionary(grouping:by:) bucketscase let (if let row, case let frame = row.frame, !frame.isEmpty)let <name> = <Type>(...))Result, optionals, and ?? state parameter and result types, as -warn-long-expression-type-checking-scopes <n> under warnings as errors fails an expression past <n> scopesswitch keeps recognition, extraction, guards, and results together. Host tokens (kAX…Role and subrole constants, flags) classify once at the boundary into the module's enum, a tuple subject making one table where each arm names a combination of its values:
enum Kind: Sendable {
case window
case dialog
case sheet
case menu
init?(role: String, subrole: String?, root: Bool, modal: Bool) {
switch (root, role, subrole, modal) {
case (true, kAXMenuRole, _, _): self = .menu
case (_, kAXSheetRole, _, _): self = .sheet
case (true, _, kAXDialogSubrole, _), (true, _, _, true): self = .dialog
case (true, _, _, _): self = .window
case (false, _, _, _): return nil
}
}
}
New Accessibility roles change one arm:
switch beside the classificationwhere clause holds a test one pattern alone readscase (.or, ..<compound.subpredicates.count), (_, 0): nil dropping a predicate)Swift guarantees no tail calls, and depth bound and successor sharing select the form:
| [INDEX] | [FORM] | [USE_WHEN] |
|---|---|---|
| [01] | Direct recursion | Depth is small and bounded by the input's format |
| [02] | indirect case fold | Each child belongs to one parent |
| [03] | sequence(state:next:) | Intermediate states are values a consumer reads lazily |
| [04] | Array stack beside a Set of visits | Depth-first walk over links that repeat or cycle |
| [05] | OrderedSet worklist | Breadth-first walk over shared or cyclic successors |
| [06] | sequence(first:next:), prefix(<node count>) | Parent chain over links another process reports |
Values take the type that the standard library, an SDK framework, or a package in use declares for their fact. Declarations add only a rule no such type states:
| [INDEX] | [FACT] | [TYPE] |
|---|---|---|
| [01] | Values one reader groups | Labeled tuple |
| [02] | Interval | Range, ClosedRange |
| [03] | Positions a test selects | RangeSet |
| [04] | Elapsed time, instant | Duration, ContinuousClock.Instant |
| [05] | Identity | UUID, Identifiable.ID |
| [06] | File location | FilePath, URL |
| [07] | File format | UTType |
| [08] | Host failure code | Errno, AXError, OSStatus |
| [09] | Sort order | KeyPathComparator<T> |
| [10] | Vector | SIMD2<Double> |
| [11] | Rendered text | formatted() with the value's format style |
RawRepresentable structs hold a value's rule in init?(rawValue:), and the standard library's coder for their raw type refuses a rejected value at decodeRawRepresentable fields synthesize each initializer and coder, a field computed from stored fields is a computed propertydescription, a message) goeskCFBundleIdentifierKey, UTType, String(describing: T.self), a rawValue, a Mirror case label).units for a Duration, .byteCount, .list, .iso8601), and a call site passes the value alonenil of an Optional, never an empty string, a sentinel, a force cast, or a force unwrap"" included where an API reads it as unsetEnums declare a closed set, and one switch returns every host constant a case maps to as a labeled tuple. Reverse lookups build once from allCases into a static dictionary:
enum Special: CaseIterable, Sendable {
case `return`
case tab
case escape
private static let glyphs: [Int: Self] = Dictionary(uniqueKeysWithValues: allCases.map { special in (special.codes.glyph, special) })
init?(glyph: Int) {
guard let special = Self.glyphs[glyph] else { return nil }
self = special
}
var codes: (key: CGKeyCode, glyph: Int) {
let (key, glyph): (Int, Int) =
switch self {
case .return: (kVK_Return, kMenuReturnGlyph)
case .tab: (kVK_Tab, kMenuTabRightGlyph)
case .escape: (kVK_Escape, kMenuEscapeGlyph)
}
return (CGKeyCode(key), glyph)
}
}
kVK_* and kMenu*Glyph come from Carbon's HIToolbox. Menu shortcuts read back as keys through init?(glyph:), and a new case cannot miss a column.
Choose collections by their most frequent operation:
| [INDEX] | [OPERATION] | [COLLECTION] |
|---|---|---|
| [01] | Ordered reads, appends | Array |
| [02] | Keyed lookups with insertion order read | OrderedDictionary, OrderedSet |
| [03] | Values interned to dense ids | OrderedSet, append(_:) returns the index |
| [04] | Keyed lookups, membership | Dictionary, Set |
| [05] | Insertion and removal at both ends | Deque |
| [06] | Repeated minimum or maximum | Heap |
| [07] | Many versions sharing structure | TreeDictionary, TreeSet |
| [08] | Dense small non-negative integers | BitSet |
Each state a consumer inspects is a distinct case. Counting a type's values (struct fields multiply, enum cases add, Optional adds one) exposes states no consumer reaches:
Result each, an optional pair or a reason string loses which outcome failed@CasePathable with @dynamicMemberLookup reads one case (fact.integer, message[case: \.state], state.is(\.exited)), and switch decides every caseOne form serves one concern:
| [INDEX] | [FORM] | [CONCERN] |
|---|---|---|
| [01] | T? | Absence with no reason |
| [02] | throws(E) -> T | Expected failure of a step |
| [03] | async throws(E) -> T | Expected failure of a step that suspends |
| [04] | Result<T, E> | Outcome stored, collected, or handed to a callback as a value |
| [05] | Result<T, AggregateError<E>> | Independent steps the whole needs, every failure kept |
| [06] | Record of successes, failures | Items read independently, each kept |
| [07] | some AsyncSequence<T, E> | Values over time with one failure that ends the sequence |
| [08] | Task<Result<T, E>, Never> | Work started now and joined later, its typed outcome a value |
Step signatures and the dependence between steps select the operator:
| [INDEX] | [SIGNATURE] | [OPERATOR] | [BEHAVIOR] |
|---|---|---|---|
| [01] | T -> U | map | Transforms a present value, keeps the form |
| [02] | T -> U? | flatMap, compactMap | Continues with a step that can find nothing |
| [03] | T throws(E) -> U | One try over the expression | Continues with a dependent step, first throw ends it |
| [04] | Independent aggregate Results | combine over a pack | Runs every step, keeps every failure together |
| [05] | [T] with T throws(E) -> U | map with a throwing closure | Stops at the first failure |
| [06] | [T] with an aggregate step | traverse | Runs every step, keeps every success or failure |
One shared module declares AggregateError with its combine and traverse members, and aggregated, which lifts one step's failure into an aggregate, for every module:
Each throwing module declares one error type: a struct holding the rejected subject and a @CasePathable reason enum. One protocol extension derives every module error's text from its subject, its reason's case label, and the values that case holds:
public protocol ModuleError: CustomNSError, LocalizedError {
associatedtype Reason: Sendable
var subject: String { get }
var reason: Reason { get }
}
extension ModuleError {
public var errorDescription: String? {
func fact(_ value: Any) -> String? {
let mirror: Mirror = Mirror(reflecting: value)
let separator: String? =
switch mirror.displayStyle {
case .optional?, .tuple?: " "
case .collection?, .set?, .dictionary?: ", "
default: nil
}
let parts: [String] = separator == nil ? [] : mirror.children.compactMap { fact($0.value) }
return switch (value, separator) {
case (let duration as Duration, _): duration.formatted(.units(width: .narrow))
case (let error as any ModuleError, _): error.errorDescription
case (let error as NSError, _) where type(of: value) is NSError.Type: error.localizedDescription
case (_, let separator?): parts.isEmpty ? nil : parts.joined(separator: separator)
case (_, nil): String(describing: value)
}
}
let held: Mirror.Child? = Mirror(reflecting: reason).children.first
let label: String = held?.label ?? String(describing: reason)
let words: String = label.replacing(/\p{Lu}/) { " " + $0.output.lowercased() }
return [subject, words, held.flatMap { fact($0.value) }].compactMap(\.self).joined(separator: " ")
}
}
public struct FileFailure: ModuleError, Equatable {
@CasePathable
public enum Reason: Equatable, Sendable {
case held
case waited(Duration)
case filesystem(NSError)
}
public let subject: String
public let reason: Reason
public var errorUserInfo: [String: Any] {
switch reason {
case .filesystem(let error): [NSUnderlyingErrorKey: error]
case .held, .waited: [:]
}
}
}
Mirror reads the thrown case's label and payload, a new case or module adds no text, and the extension is the one place a failure's text changes form:
localizedDescription and a bridged NSError read errorDescription, and errorUserInfo holds the host cause under NSUnderlyingErrorKeyError refines Sendable, every reason fact is Sendable, and a cause crosses tasks wholenotOnConsole prints not on console), , and a nil or a part formatting to nothing drops outDuration by .units, a nested ModuleError by its own errorDescription, an NSError instance by localizedDescriptionNSError among them, print through String(describing:)nil shared across rules loses which rule failed.notOpen(nearest:))Errno.description, GetMacOSStatusErrorString), and AXError and CGError, which no host member names, keep one name per coderecoverySuggestion of their own errorErrno from System, AXError, DecodingError, and NSError for an untyped Foundation throwNSError is Sendable and Hashable, and a reason holding one synthesizes Equatable where any Error forces a hand ==do holds the host call alone and its catch throws the module errorAXObserverAddNotification result leaves a refused registration silentotherwise: () -> Self closure makes the extra host read a fall-through case alone needs.readBack)do throws(E) (catch let error where error.reason.is(\.held)), and the rest propagatetry? hiding a cause go, and a Result field keeps a cause a reader reportsCancellationError passes through as the cancelled outcome, consumers classify by reason, and cleanup a cancelled task must finish runs under withTaskCancellationShieldIsolation decides where code runs and what it touches, and the state a value shares selects the form:
| [INDEX] | [STATE] | [FORM] |
|---|---|---|
| [01] | No mutable state shared | Sendable values and nonisolated functions |
| [02] | State the user interface reads | @MainActor types and functions |
| [03] | Shared mutable state whose updates suspend | actor |
| [04] | Non-Sendable host handles | actor holding the handles, Sendable records leaving it |
| [05] | Blocking host calls over actor-held state | actor whose unownedExecutor is its own DispatchSerialQueue |
| [06] | Shared mutable state updated synchronously | Mutex or Atomic in a final class: Sendable |
| [07] | Same state held by a copyable value | OSAllocatedUnfairLock |
| [08] | CPU-bound work off the caller's actor | @concurrent function |
| [09] | Nonisolated blocking host call | @concurrent function under withTaskExecutorPreference(<queue>) |
Child tasks follow the shape of the work, and each child returns its typed Result for its parent to decide once:
| [INDEX] | [WORK] | [FORM] |
|---|---|---|
| [01] | Fixed number of independent steps | async let |
| [02] | Dynamic number of steps with results | withTaskGroup over Result<T, E> |
| [03] | Dynamic number of steps, no results | withDiscardingTaskGroup |
| [04] | Work that outlives the calling scope | Task its owner stores and cancels |
Delivery shape selects source and operator:
| [INDEX] | [DELIVERY] | [FORM] |
|---|---|---|
| [01] | Host callback delivering values | AsyncStream.makeStream, release in onTermination |
| [02] | Host notifications | NotificationCenter.messages(of:for:) |
| [03] | Changes of an @Observable model | Observations |
| [04] | Sources merged into one | merge, combineLatest, zip, chain |
| [05] | Bursts | debounce(for:) |
| [06] | Batches | chunks(ofCount:), chunked(by:) |
| [07] | Producer paced by the consumer | AsyncChannel |
| [08] | Consumers sharing one source from now on | share(bufferingPolicy:), no replay |
| [09] | Subscribers taking the current value first | Owning actor yields its state and stores the continuation in one step |
| [10] | Lines of a child process | strings(separatedBy:bufferingPolicy:) |
| [11] | State with no event | AsyncTimerSequence(interval:clock:).first(where:) |
| [12] | Elements until an event | merge with the event as nil, prefix(while:) |
| [13] | One event an act causes, or a timeout | first { _ in true } of a stream opened before the act, withTimeout |
flatMapLatest traps at a state precondition when an outer element races its inner sequence's end, and row [12] replaces it. Request-response work and one-shot waits stay an async throws(E) function. One-shot waits whose typed failure has no cancelled case (Errno) are a one-element stream, and a cancelled consumer ends it with no element.
Values entering a module decode once into their model type, and values leaving encode from it:
Lenient<Known> fields (a known case or the raw value), as Lenient<AXError> keeps a code the SDK leaves unnamedCodable holds every wire mapping, and init(from:) is hand-written only where a stored type lacks Codable or a field names the caseencode(to:) writes through a keyed container over CodingKeys, and a dictionary literal drops fields it omitsCFTypeRef) decode in one failable init switching on CFGetTypeID into a closed enum with one case per host typeAXUIElementCopyAttributeNames leaves the rest unreadAXUIElementCopyMultipleAttributeValues), and consumers take the read recordCGImageSourceCreateThumbnailAtIndex under kCGImageSourceThumbnailMaxPixelSize scales an image, and RecognizeTextRequest boxes map through toImageCoordinatesUTType(filenameExtension: file.pathExtension)) in place of a format parameter restating itSCRecordingOutputConfiguration().outputFileType) in a system temporary folder, and the caller receives DataFileDescriptor and Errno from System state the host's file API and its failuresGeneric code states the capability it reads, and the call site's knowledge of the concrete type selects the form:
| [INDEX] | [KNOWLEDGE] | [FORM] |
|---|---|---|
| [01] | One concrete type per call, fixed by the caller | some Protocol<Assoc> parameter |
| [02] | One concrete type returned, hidden from the caller | some Protocol<Assoc> return |
| [03] | Different concrete types in one collection or field | any Protocol<Assoc> |
| [04] | Relation between types across parameters | Named generic parameters with where |
| [05] | Any number of types, each kept distinct | Parameter pack (each T), combine |
protocol Store<Item>), and signatures constrain them without a where clausereferences/boundaries.md (opens in a new tab)references/concurrency.md (opens in a new tab)references/data.md (opens in a new tab)references/functions.md (opens in a new tab)references/generics.md (opens in a new tab)references/interoperability.md (opens in a new tab)references/ownership.md (opens in a new tab)references/results.md (opens in a new tab)references/streams.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub bsamiee/rasm --plugin swift3 skills in this plugin
/debuggingUse when Swift code misbehaves at runtime and its cause is unproven (failing or crashing test, trap, thrown error, hung task, data race, executor violation, leak), covering Swift sessions of the debugger server, test runners, error and failure stops, sanitizers, backtraces, and dSYMs/testingUse when writing, running, or debugging Swift tests, covering Swift Testing traits, expectations, arguments, exit tests, attachments, generated inputs, privacy grants, XCTest performance metrics, and CI