Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Swift Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-swift-knowledge-patch)
---
name: swift-knowledge-patch
description: Swift
version: "6.4"
license: MIT
metadata:
author: Nevaberry
---
# Swift compatibility guidance
Load this skill when migrating Swift code or working with actor isolation,
memory safety, C-family imports, SwiftPM, Embedded Swift, testing, or DocC.
Use the quick reference for common decisions and the topic files for complete
conditions and examples. Historical syntax retains its stated Swift version.
## Reference index
| Reference | Topics |
| --- | --- |
| [C-family interoperation](references/c-family-interop.md) | C and Objective-C implementations, C++ lifetimes, bounds, API Notes, imported names, ownership, and pointers |
| [Concurrency and isolation](references/concurrency.md) | Actor defaults, conformances, caller isolation, tasks, cleanup, task locals, messages, and observation |
| [Embedded Swift](references/embedded-swift.md) | Library support, restrictions, key paths, emitted symbols, linkage, MMIO, and LLDB |
| [Language and library](references/language-and-library.md) | Lookup, closures, associated types, safety, key paths, initialization, collections, spans, and optimization |
| [Packages, builds, and platforms](references/packages-builds-and-platforms.md) | Traits, warning policies, migration, build engines, plugins, interfaces, deployment, and availability |
| [Testing, documentation, and tools](references/testing-documentation-and-tools.md) | Swift Testing, XCTest, exit tests, attachments, DocC, SourceKit, editor integration, and debugging |
## Migration and compatibility checks
### Source semantics and deprecated syntax
- In Swift 6.4, associated types can declare `~Copyable` or `~Escapable`.
Migrate the deprecated `SuppressedAssociatedTypes` experiment: its syntax
is source-incompatible with the accepted feature.
- Swift 6.4 rejects forward references to locals from closures, including
lazy local initializers, initializers moved into accessors by macros, and
captures of local computed variables. Declare the local before the closure,
or qualify an intended member reference with `self.`.
- In Swift 6.4, an unqualified closure name resolves to an instance member
before a same-named local is in scope, including in the local's own
initializer. After the declaration, it resolves to the local.
- The upcoming `MemberImportVisibility` feature makes imported extension
members available according to each file's imports. If a member becomes
unavailable, import its defining module in the calling file.
- In Swift 6.1, `checkValue($value: binding)` calling
`func checkValue(@Binding value: Int)` invokes `Binding.init(projectedValue:)`
even when `binding` already has the matching wrapper type. Account for
validation or other initializer effects.
- From Swift 6.2, an enclosing declaration's unavailability on a platform
skips that platform's minimum-version checks inside it. If another exposed
overload makes a call ambiguous, use an explicit argument type.
### Actor and task migration
- `NonisolatedNonsendingByDefault` makes nonisolated async declarations and
function types run on the caller's actor. Explicit `nonisolated(nonsending)`
selects that behavior with either flag setting. Mark an existing async
function `@concurrent` to preserve its hop off the caller's actor.
- Inside a `nonisolated(nonsending)` async function, `#isolation` can forward
the caller's actor to an `isolated (any Actor)?` parameter. A plain
`Task { ... }` created inside the function starts nonisolated.
- Imported Objective-C completion-handler parameters are `@Sendable` by
default; Swift checks captures in closures passed to them. Qualifying
nonisolated Objective-C completion-handler methods import as async
`nonisolated(nonsending)` regardless of the upcoming-feature flag.
- Swift (next) allows actors to conform to global-actor-isolated protocols
and stops inferring global-actor isolation on actors from property wrappers
or protocols with inferred isolation. Annotate affected static methods or
initializers that still need that global actor.
- Swift 6.4 throwing unstructured task initializers support typed errors and
diagnose discarded throwing tasks under `NoUseUnstructuredThrowingTask`.
Keep the handle to observe its result, or explicitly discard with `_ =`
when intentional.
- In Swift 6 language mode, a task local with an optional type alias needs
an explicit `= nil` default. Task locals can also be globals.
### Safety contracts and generated interfaces
- Opt-in strict memory-safety checking warns at unsafe uses without an
`unsafe` acknowledgement. Declare unsafe APIs with `@unsafe`; use `@safe`
where a declaration needs to override an unsafe classification.
- Swift 6.3 marks span `bytes` and `mutableBytes` accessors and generic
`OutputRawSpan.append` overloads `@unsafe`. Use element or appended value
types without internal or trailing padding. If mutated bytes will be read
back as elements, every bit pattern must be a valid element value.
- `RawSpan` checked-offset loads validate bounds; the caller must ensure a
valid representation for the requested type. `unsafeLoad` also needs proper
alignment. For potentially unaligned offsets, use `unsafeLoadUnaligned`
with `BitwiseCopyable` types.
- The C-family importer generates one wrapper per function. Add complete
bounds and lifetime contracts together to avoid changing its generated
signature when adding a later annotation. Bounds checks apply at the Swift
interop boundary; `-fbounds-safety` enables enforcement when compiling C code.
- Swift 6.3 library-evolution builds can opt into interface module selectors
with `-enable-module-selectors-in-module-interface` in `OTHER_SWIFT_FLAGS`.
Swift 6.4 enables them by default; opt out with
`-Xfrontend -disable-module-selectors-in-module-interface`.
## Concurrency quick reference
For a target in Swift 6 language mode, enable the two Approachable Concurrency
features in its settings. Swift 6 mode already enables
`DisableOutwardActorInference`, `GlobalActorIsolatedTypesUsability`, and
`InferSendableFromCaptures`.
```swift
.target(name: "App", swiftSettings: [
.enableUpcomingFeature("InferIsolatedConformances"),
.enableUpcomingFeature("NonisolatedNonsendingByDefault"),
])
```
- With Swift tools 6.2, use `.defaultIsolation(MainActor.self)` or compiler
flag `-default-isolation MainActor`; `nil` and `nonisolated`, respectively,
select the ordinary nonisolated default. Explicit or otherwise inferred
isolation takes precedence. Direct conformance to a protocol refining
`SendableMetatype` in the primary type declaration suppresses this inference.
- Apply `nonisolated` to a struct, class, enum, or protocol to stop it from
inheriting global-actor isolation.
- Put a global actor on a protocol conformance to let isolated members satisfy
otherwise nonisolated requirements; that conformance is usable on that actor.
Generic use requiring both the protocol and `SendableMetatype`, including
through `Sendable`, needs a nonisolated conformance to the protocol.
- `Task.immediate` runs inline up to the first suspension when the caller is
already on the task's executor. Task groups offer `addImmediateTask` and
`addImmediateTaskUnlessCancelled`; child-result inference can omit `of:`
from `withTaskGroup` and `withThrowingTaskGroup`.
- `isolated deinit` runs a synchronous deinitializer on the class's actor.
Swift 6.4 permits `await` in an async scope's `defer`, sharing that scope's
isolation. `withTaskCancellationShield` masks observation of cancellation
inside its scope; use it for deferred cleanup that would otherwise exit early
when checking cancellation.
- `Observations` batches synchronous observable-state mutations into a
transaction that ends at the next `await` that suspends.
## Package traits and warning policies
- Declare package defaults with `.default(enabledTraits:)` and let traits
activate others through `enabledTraits`. Forward a local trait with
`.when(traits:)`; dependency trait names are scoped to their package.
- Include `.default` alongside named dependency traits to keep that
dependency's defaults enabled. A target's `.product` condition can use
`traits:` and combine it with `platforms:`.
- Use `swift package show-traits` to inspect supported traits. `swift build`,
`swift run`, and `swift test` accept `--traits`, `--enable-all-traits`, and
`--disable-default-traits`.
```sh
swift test --traits Images,Animation
swift test --enable-all-traits
swift test --disable-default-traits
```
- Use migration diagnostics and suggested fix-its to preserve behavior when
enabling upcoming features. Use `-print-diagnostic-groups` to find warning
groups; flag order matters. Put `-Wwarning` after `-warnings-as-errors`
to exempt a group.
- In target settings, put `.treatWarning(_:as:)` after `.treatAllWarnings(as:)`
to keep one diagnostic group at warning severity while promoting the rest
to errors.
- Swift 6.4's `@diagnose` sets a group's severity to `error`, `warning`, or
`ignored` in a declaration's lexical scope; use `reason:` for the rationale.
- SwiftPM's C-input generation is experimental. Use
`// swift-tools-version: 6.3;(experimentalCGen)` in the package using the
plugin. A target can have one generated module map, with referenced headers
and API Notes beside it; remove any module map in its public headers path.
## C-family interoperation and storage
- Implement imported Objective-C declarations with `@objc @implementation`
on a Swift extension, keeping the header for existing callers. Use `@c` to
expose a Swift function or enum in the generated C header, or
`@c @implementation` to implement a declaration supplied by the C header.
- Mark borrowed C++ views `SWIFT_NONESCAPABLE` and independently owned types
`SWIFT_ESCAPABLE`. Use lifetime contracts to tie results to arguments or
`this`, capture input lifetime dependencies, or describe independent results.
- Experimental `SafeInteropWrappers` generates overloads for sufficiently
lifetime-annotated, top-level C++ `std::span` parameters and results. Const
elements import as `Span<T>`; mutable elements import as `MutableSpan<T>`.
- `__counted_by` describes element counts; `__sized_by` describes byte counts.
With `SafeInteropWrappers`, sufficient lifetimes yield `Span`, `MutableSpan`,
or `RawSpan`; bounds-only typed pointers yield `UnsafeBufferPointer` or its
mutable counterpart. Shared counts are inferred, trapping on unequal lengths;
`rows * columns` bounds retain both arguments and check their product.
- API Notes can control imported names, reference ownership, enum cases,
wrapper types, pointer nullability, and lifetime and bounds contracts.
See the C-family reference for field names and complete examples.
- `InlineArray` literals can infer counts and diagnose mismatched explicit
counts at compile time. `init(first:next:)` derives each element from a borrow of
the previous element, including noncopyable elements.
- `Span<Element>` is a read-only view constrained by its backing storage's
lifetime; iterate its zero-based `indices` and use its bounds-checked subscript.
## Testing, documentation, and tools
- A `TestScoping` trait can wrap execution in setup and teardown or bind a
task-local value. `#expect(throws:)` and `#require(throws:)` return the caught
error. `confirmation(expectedCount:)` accepts ranges with a lower bound.
- Record Swift Testing issues with `Issue.record` and `severity: .warning`
to allow a test to pass. `try Test.cancel()` cancels the running test and
its task hierarchy; in parameterized tests, call it in the case to skip.
- Exit tests use `processExitsWith:`; `observing:` captures standard output
or error as `[UInt8]`. Exit-test closures can capture parent-test values.
- `Attachment.record` accepts strings; byte arrays, slices, and contiguous
arrays are also attachable. Import `Foundation` alongside `Testing` for
`Data`, or to use `Encodable` or `NSSecureCoding` with `Attachable`.
Cross-import overlays for UI frameworks support image attachments,
with image attachment support also available on Windows.
- DocC overload links can use parameter types, return type, or both, with
`_` for an omitted parameter type. Experimental `docc convert` flags enable
Markdown output, static HTML summaries, and code-block annotations.
- SourceKit-LSP enables background indexing by default for SwiftPM projects.
Swift 6.1 syntactic SourceKit queries omit inactive `#if` branches;
tools needing all branches can parse with SwiftSyntax.
- LLDB can step into async functions across thread switches and show task
context. The official editor extension is `swiftlang.swift-vscode`.
## Embedded Swift and deployment
- Embedded Swift supports the full `String` API, class-constrained protocol
existential values, `InlineArray`, and `Span`. Floating-point types expose
`description` and `debugDescription`.
- Swift (next) supports Embedded key paths, including ones surviving compile-time
evaluation. Runtime captures can allocate; `KeyPathAllocation` diagnoses sites.
- Embedded builds enable `EmbeddedRestrictions` by default. In regular builds,
use `-Wwarning EmbeddedRestrictions` or the target's SwiftPM warning settings.
- Embedded linkage coalesces shared-module definitions in diamond dependencies,
removing the need for `-mergeable-symbols` and `-emit-empty-object-file`.
- Swift supports WebAssembly client and server deployment to browsers or other
Wasm runtimes. The official Android SDK builds native programs and packages;
use `swift-java` and `swift-java-jni-core` for Kotlin or Java integration.