/swift:modeling-swift-types-for-correctnessfrom Swift
Models Swift type-system invariants, validated decoding, legal state transitions, ownership, and generic relationships. Load before assessing or changing enforcement boundaries.
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.
Use Swift’s type system to remove invalid operations and state combinations from ordinary code paths. Prefer the lightest representation that produces a useful diagnostic at the misuse site.
This skill owns Swift representation and its enforcement: construction, decoding, interop, ownership, and compiler evidence. The concurrency skill owns scheduling, isolation repair, and task lifecycle; the shared feature-status reference owns dated support and availability facts. First distinguish a representation or enforcement claim from ordinary function behavior: testing a function's outputs, even with negative or boundary inputs, does not itself call for type modeling or invariant verification. Keep that work with the testing or defect-review skill.
For a representation claim or a change to an enforcement boundary, invoke verifying-invariants if installed and not already active. Apply its procedure alongside the Swift rules here, including for a small initializer or decoding fix with a settled predicate. When Universal is absent, use this skill's Swift checklist and report the assessment's limits.
Swift cannot prove arbitrary facts about runtime input before validation. Refine untrusted input at a boundary, then pass the refined value inward. A validating initializer proves nothing if another initializer, decoder, mutation, or bridge bypasses it.
Inspect the environment when compiler behavior, availability, isolation, or ownership affects the claim. For a supplied snippet without a project, state unknown settings briefly and assess its shown boundaries. Do not infer language features from the deployment target:
xcrun swift --version.Resolve all bundled script, fixture, and reference paths relative to this skill directory; run project commands from the consumer repository.
Run python3 scripts/audit_project.py <project-root> for a heuristic inventory, then verify target-specific Xcode settings. The bundled compiler fixtures use Swift 6 language mode. Assess production code under its actual supported settings; a different language mode is a verification limit, not permission to migrate.
Preserve the project’s actual runtime lane. The following iOS 16 examples illustrate compatibility choices, not a mandatory deployment minimum:
Use #if canImport(Module) for module presence, @available and if #available for runtime APIs, and #if compiler(...) only when the repository deliberately tests two current compiler channels. Never use #if os(iOS) as a version check or add branches for an older language mode. Read iOS versioning when deployment spans iOS 16 through current or beta SDKs.
Apply the settled invariant to Swift with these defaults:
| Invalid operation or state | Swift representation |
|---|---|
| Mutually exclusive flags or correlated optionals | Enum with associated values |
| Values that must change together | Struct with one mutation authority |
| Swappable same-representation IDs | Nominal wrapper; use a module-owned phantom tag only when several domains share behavior |
| Runtime-refined input | Immutable private storage plus a throwing or failable initializer |
| State-dependent operations | Separate state structs; use typestate when shared representation and transitions justify it |
| Trusted-issued permission | Private-initializer capability value backed by a service or actor when authority is dynamic |
| Cross-task mutable state | Actor; choose a lock only for required synchronous semantics or measured performance |
| Closed local failure surface | Small error enum or typed throws |
| Copying or reuse after consumption | Scoped operation first; verified ownership types only when lifetime is the invariant |
| Fixed-size storage | Tuple or small domain struct until measurement and availability justify a specialized layout |
A comment, typealias, naming convention, boolean permission, RawRepresentable, or freely conformable marker protocol documents intent without enforcing it.
Before assessing or recommending a representation, read the focused reference for the claim, even for a read-only design sketch. The skill body does not replace these construction rules and proof limits:
For other concerns, use the Reference Map; use the decision guide when pattern selection remains open. Load only relevant sections and consult feature status only for mechanisms that depend on recent support.
Keep validated values immutable. Expose one obvious checked constructor and keep any unavoidable unchecked path narrowly scoped, loudly named, and documented with its precondition.
Audit every route that can create or invalidate the value:
RawRepresentable initializers.Decodable, persistence hydration, macros, reflection, and fixtures.NSCoding, NSCopying, C/C++ imports, raw handles, and unsafe pointers.@unchecked Sendable, unchecked factories, unsafeBitCast, force casts, force unwraps, and unchecked indexes.Confirm synthesis before alleging a bypass: a struct's custom initializer in its primary body suppresses memberwise synthesis; one in an extension does not. Visible let storage is still immutable. Neither fact seals synthesized decoding. Synthesized Encodable does not rerun the validating initializer; an invalid decoded instance can therefore be encoded again. Check saving claims against values admitted by every construction path.
Do not use ExpressibleByStringLiteral when validation can fail unless a macro checks literals or an explicit trap policy governs them. Do not describe a nominal wrapper as authorization or security enforcement.
Keep raw, validated, and presented representations distinct:
JSON / database / Objective-C / user input
-> raw DTO or foreign shape
-> validation and canonicalization
-> domain type
-> view or transport projection
Decode malformed external data into a raw shape, attach boundary context to failures, then call the same checked constructor used by in-memory callers. Custom Decodable is appropriate when wire and domain shapes coincide, but its implementation must reuse that constructor. Verify synthesized decoding before relying on private storage as a seal.
Before suggesting or changing a decoder, read the keyed decoding example and establish the existing wire contract:
value: Int, decode through decoder.container(keyedBy: CodingKeys.self) and decode(Int.self, forKey: .value). A singleValueContainer() would change that wire contract.Run the checks when execution is in scope. Keep one record for each of the three controls, with its observed evidence and result or its pending status, including in a read-only assessment. Derive any summary of what ran from those records. A round trip can pass while the defect exists and still belongs in the repair's regression checks: it guards encoder/decoder agreement. Keep it distinct from the historical payload control.
Describe a decoder repair with its container and keys as well as its validation path. If showing concrete decoder code, compile that exact proposal with the unchanged encoder and run the three controls when execution is available. Use the applicable project checks, or isolated scratch code for read-only work; existing equivalent checks suffice. This catches incompatible container APIs as well as schema changes. If execution is unavailable, distinguish the proposed implementation from a checked repair.
For scratch compiler checks, keep allocation, cleanup registration, compilation, and execution in one tool command, outside the project. Use a scoped temporary-directory API or register an exit trap immediately after allocation; see scratch compiler checks. Cleanup must cover failure too. Report runs, changes, and cleanup only when completed tool results confirm them.
Read boundaries and interop for networking, persistence, notifications, Objective-C, C, analytics, and public resilience.
Introduce the domain type and runtime tests, then change the innermost operation to require it. Follow compiler errors outward, constructing the value at raw input boundaries. Remove or deprecate raw overloads once callers migrate. Keep compatibility and availability adapters at module boundaries rather than spreading them through core logic.
Avoid generic typestate when separate concrete types produce clearer call sites and diagnostics. Remove a type axis when it worsens build time or developer understanding without preventing a meaningful misuse.
Compiler checks complement runtime tests; they do not replace them. A compile-fail fixture establishes only that the recorded source snapshot, compiler, phase, and arguments reject the listed misuse with the expected diagnostic. It does not prove runtime validation, decoding behavior, availability, synchronization, interop, security, or all possible construction routes.
For valuable static guarantees, compile the real production module or the shared production sources plus a small misuse fixture. Pair every negative fixture with a valid control using the same compiler phase and shared compiler arguments; fixture sources and output paths may differ. Record each side’s effective phase and arguments, and derive the report from those records. After changing the phase or shared arguments, rerun the positive control. If the controls differ, report the difference and the missing pairing instead of describing the invocations as identical. Use an emit-module pipeline when ownership checking matters; a type-check-only invocation can miss ownership-flow diagnostics. Reject an unexpected acceptance, missing or unrelated diagnostic, broken positive control, compiler crash, and timeout.
This skill includes a reusable standard-library runner:
python3 scripts/swift_compile_checks.py examples/compile-checks.json
python3 scripts/swift_compile_checks.py examples/compile-checks.json --json
The manifest records minimum compiler version, compiler arguments, shared support sources, paired positive controls, negative fixtures, and diagnostic markers. The report records the resolved toolchain, manifest digest, inputs, results, and limitations. A missing, unparseable, or too-old compiler is unavailable, never a successful proof. scripts/check_examples.sh retains the optional legacy skip; set REQUIRE_SWIFTC=1 to make unavailability fail. Read the compile-check runner contract before creating or integrating another manifest.
Use the existing Swift testing skills for test structure and deterministic synchronization. They own runtime assertions, async readiness, completion signals, bounded waits, cancellation, and cleanup. Read testing, migration, and review for Swift-specific fixture design, serialization, availability, performance, migration, and review guidance.
For a verification-only request, report the boundaries, counterexamples, checks, and limits. Include replacement code or a migration design only when the user asks for repair or implementation advice.
Report, in proportion to the task:
Classify conclusions precisely:
Before returning an invariant assessment or enforcement-boundary change, confirm that verifying-invariants has been loaded when installed. If it was skipped, load it and reconcile the evidence and conclusion before finishing. Use the standalone checklist below when it is unavailable.
Decodable result transfers only to paths shown to invoke that decoder. Uninspected paths remain explicit limits.Load the owner of the changed concern. Mechanism guides explain construction and language rules; recipes apply those rules to compound invariants. Follow their conditional links only when that supporting detail is needed:
For bundled scripts, fixture sources, and activation/quality evals, see the utility inventory.
references/swift-feature-status.md)ATTRIBUTION.md (opens in a new tab)agents/openai.yaml (opens in a new tab)evals/quality-evals.md (opens in a new tab)evals/trigger-evals.json (opens in a new tab)examples/CompileFailBypassValidation.swift (opens in a new tab)examples/CompileFailUseAfterConsume.swift (opens in a new tab)examples/CompileFailWrongID.swift (opens in a new tab)examples/CompileFailWrongTrustState.swift (opens in a new tab)examples/CompileFailWrongTypestate.swift (opens in a new tab)examples/CompilePassCorrectID.swift (opens in a new tab)examples/CompilePassCorrectTrustState.swift (opens in a new tab)examples/CompilePassSingleConsumption.swift (opens in a new tab)examples/CompilePassValidTypestate.swift (opens in a new tab)examples/CompilePassValidatedConstruction.swift (opens in a new tab)examples/CorePatterns.swift (opens in a new tab)examples/CorePatternsRuntimeChecks.swift (opens in a new tab)examples/CurrentSwiftPatterns.swift (opens in a new tab)examples/TrustStatePatterns.swift (opens in a new tab)examples/compile-checks.json (opens in a new tab)examples/compiler-corpus-controls.json (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub kylehughes/agent-plugins-for-making-good-software --plugin swift10 skills in this plugin
/designing-swift-apisDesign Swift API names, labels, signatures, and documentation contracts. Use proactively when adding or changing APIs or reviewing call-site clarity against Apple's API Design Guidelines./ordering-symbolsOrder Swift members by declaration kind, access, and name when semantics permit. Use proactively when adding or moving members; preserve initialization, enum, UI, and other meaningful order./organizing-swift-typesOrganize Swift types, conformances, extensions, access control, and files. Use proactively when adding or restructuring declarations; apply repository conventions before the suggested layout./structuring-swift-packagesStructure Swift package boundaries, dependencies, exports, and composition roots. Use proactively for module placement or dependency cycles; preserve the repository’s architecture and naming./testing-async-swift-codeMake Swift async tests deterministic. Use proactively for timing, observer readiness, completion, cancellation, cleanup, or flaky tests; not general test organization./testing-swift-codePlan or write Swift unit tests with Swift Testing. Use proactively for regression coverage, assertions, suites, traits, or migration; async timing has its own skill and UI tests use XCTest.Other plugins' skills for the same job