lang-swift
Use when the user asks about Swift 6, strict concurrency, actors, Sendable, MainActor, data race errors, async let, ARC and retain cycles, weak self, typed…
от j4flmao★ 47 звёзд на GitHub
Установить lang-swift в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Об этом скилле
Swift
Purpose
Swift combines value semantics, protocol-oriented design and automatic reference counting with compile-time data-race safety in the Swift 6 language mode. Migration pain and bugs cluster around concurrency isolation, Sendable, retain cycles and force-unwrapping. This skill covers current idioms (Swift 6.x) for those areas.
Agent Protocol
Trigger
"Swift", "Swift 6", "strict concurrency", "actor", "Sendable", "async let", "MainActor", "protocol-oriented", "value types", "ARC", "retain cycle", "weak self", "optionals", "SwiftPM", "Swift Testing", "typed throws".
Input Context
- Swift toolchain / Xcode version and language mode (Swift 5 with concurrency checking, or Swift 6)
- Platform (iOS/macOS app, server on Linux, package/library)
- Compiler diagnostics being fixed, if any
Output Artifact
Swift code, Package.swift settings, or an explanation of a concurrency diagnostic with the fix. No file unless requested.
Response Format
Toolchain/mode: {Swift 6.2, language mode 6}
Change: {what and why}
Code: {snippet}
Isolation: {which actor each piece runs on; why types are Sendable}
Verify: {swift build / swift test, Thread Sanitizer, Instruments}
1. Optionals
T?must be unwrapped:if let x,guard let x else { return },??defaults, optional chaininga?.b?.c.- Force unwrap
!and implicitly unwrapped optionals only where an invariant guarantees a value (e.g.@IBOutletafter load); otherwise crash risk.
2. Value vs Reference Semantics
struct/enumare value types: copies are independent (standard collections use copy-on-write so copying is cheap until mutation). Value types are not guaranteed to live on the stack — storage is the compiler's choice.classandactorare reference types with identity, managed by ARC.- Default to structs for models and state; use classes for shared identity, inheritance, or Objective-C interop.
- Noncopyable types (
~Copyable) express unique ownership (file descriptors, tokens) withconsuming/borrowingparameters.
3. Protocols and Generics
protocol Repository {
associatedtype Item: Identifiable
func fetch(id: Item.ID) async throws -> Item
}
func load<R: Repository>(_ repo: R, ids: [R.Item.ID]) async throws -> [R.Item] {
try await withThrowingTaskGroup(of: R.Item.self) { group in
for id in ids { group.addTask { try await repo.fetch(id: id) } }
return try await group.reduce(into: []) { $0.append($1) }
}
}
some Protocol(opaque, static dispatch) vsany Protocol(existential box, dynamic dispatch) — prefersome/generics in hot code;anyis explicit since Swift 5.6 and required for existentials with associated types.- Protocol extensions provide default implementations; composition over class inheritance. (The generic call above needs
R: Sendableunder Swift 6 checking because the task closures capturerepo.)
4. ARC and Retain Cycles
- Strong reference cycles (object ↔ closure, parent ↔ child, delegate) leak. Break them with
weak(optional, becomes nil) orunowned(non-optional, crashes if the object is gone — use only when lifetimes are guaranteed). - Escaping closures stored on
selfcapture it strongly:{ [weak self] in guard let self else { return } ... }. Task { }keeps capturedselfalive until the task finishes; cancel long-running tasks when the owner goes away.- Find leaks with Xcode's Memory Graph debugger and Instruments Leaks/Allocations.
5. Structured Concurrency
async/await,async letfor a fixed number of concurrent children,TaskGroupfor dynamic fan-out; child tasks are cancelled with their parent.Task.detachedonly when you explicitly need no inherited context.- Cancellation is cooperative: check
try Task.checkCancellation()orTask.isCancelledin long loops. - Actors serialise access to their mutable state; calls from outside are
awaited. Actor methods are re-entrant: state can change across anawaitinside the actor — re-check invariants after suspension. @MainActorfor UI state and UI-facing types.
actor ImageCache {
private var store: [URL: Data] = [:]
func data(for url: URL, loader: @Sendable (URL) async throws -> Data) async throws -> Data {
if let hit = store[url] { return hit }
let data = try await loader(url) // suspension: another call may fill the cache meanwhile
store[url] = data
return data
}
}
Swift 6 data-race safety
- The Swift 6 language mode turns data-race diagnostics into errors. Values crossing isolation domains must be
Sendable(value types of Sendable members are implicitly Sendable; final classes with immutable state can conform;@unchecked Sendableis a promise you must back with locking). sendingparameters/results (Swift 6) allow transferring non-Sendable values when the compiler can prove no other reference remains.- Swift 6.2 "approachable concurrency": opt-i
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
- references/protocol-associated-types.md
- references/swift-advanced.md
- references/swift-fundamentals.md
- references/swift-testing.md
FAQ
Что делает скилл lang-swift?
Use when the user asks about Swift 6, strict concurrency, actors, Sendable, MainActor, data race errors, async let, ARC and retain cycles, weak self, typed throws, SwiftPM or Swift Testing. Produces idiomatic Swift 6 code and tests. Not for iOS app architecture and SwiftUI screens (use ios) or Vapor servers (use vapor-backend).
Как установить скилл lang-swift?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл lang-swift запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
AnthropicCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
discernment-nudge
AnthropicAfter you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
data-consolidate
AnthropicJoins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
inspection-to-capa
AnthropicRuns the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…