swift
БесплатноБез исполняемых скриптовНе проверенSwift language fundamentals (5.10+ / 6.x). Covers optionals, value vs reference semantics, protocols & generics, Swift Concurrency (async/await, actors…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Swift Core Knowledge
References: concurrency.md for async/await, actors, Sendable, structured tasks. interop.md for ObjC, C, and Rust (cinterop) bridging, Keychain, Secure Enclave.
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:swift.
Optionals
var name: String = "Alice" // Non-optional
var maybe: String? = nil // Optional (sugar for Optional<String>)
// Force-unwrap (avoid)
let n = maybe! // Crash if nil
// Optional binding
if let n = maybe {
print("got \(n)")
}
// Guard (early exit)
func greet(_ name: String?) {
guard let name else { return }
print("Hello, \(name)")
}
// Nil coalescing
let display = maybe ?? "Anonymous"
// Optional chaining
let len = maybe?.count // Int?
Use guard let name else { ... } (Swift 5.7+) — implicit shadow shorter than guard let name = name else.
Value vs Reference Types
| Kind | Semantics | Allocation | Use for |
|---|---|---|---|
struct |
Value (copied on assign/pass) | Stack (usually) | Models, lightweight data, thread-safe by default |
enum |
Value | Stack | Discriminated unions, sealed states |
class |
Reference (shared identity) | Heap | Identity, inheritance, ObjC interop |
actor |
Reference + isolated | Heap | Mutable state across concurrency |
struct Point { var x: Double; var y: Double }
var a = Point(x: 1, y: 2)
var b = a // copy
b.x = 10
// a.x still 1, b.x is 10
class Node { var value: Int = 0 }
let n1 = Node()
let n2 = n1 // same instance
n2.value = 42 // n1.value also 42
Default to struct. Use class only for identity, mutable shared state, or ObjC inheritance.
Enums with Associated Values
enum NetworkResult<Success> {
case success(Success)
case failure(NetworkError)
case loading
}
enum NetworkError: Error {
case unauthorized
case server(code: Int, body: String)
case timeout(after: TimeInterval)
}
func handle<T>(_ result: NetworkResult<T>) -> String {
switch result {
case .success(let value):
return "ok: \(value)"
case .failure(.unauthorized):
return "login"
case .failure(.server(let code, _)):
return "server \(code)"
case .failure(.timeout(let t)):
return "timeout \(t)"
case .loading:
return "loading"
}
}
switch is exhaustive — no default needed when all cases covered. Compiler enforces.
Protocols & Generics
protocol Identifiable {
associatedtype ID: Hashable
var id: ID { get }
}
struct User: Identifiable {
let id: Int
let name: String
}
// Protocol-oriented design
protocol Drawable { func draw() }
extension Drawable where Self: Identifiable, Self.ID == Int {
func describe() -> String { "drawable id=\(id)" }
}
// Generic constraints
func first<C: Collection>(_ c: C) -> C.Element? where C.Element: Equatable {
c.first
}
// Existential ('any') vs opaque ('some')
func makeShape() -> some Drawable { Circle() } // concrete type, hidden
func loadShapes() -> [any Drawable] { [Circle(), Square()] } // heterogeneous
Prefer some over any — opaque types preserve type identity for the compiler (no boxing). Use any only when truly heterogeneous.
Codable
struct User: Codable {
let id: Int
let name: String
let email: String?
let createdAt: Date
enum CodingKeys: String, CodingKey {
case id, name, email
case createdAt = "created_at"
}
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
decoder.keyDecodingStrategy = .convertFromSnakeCase // alternative to CodingKeys
let user = try decoder.decode(User.self, from: jsonData)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data = try encoder.encode(user)
For BHODL-style FFI, prefer Codable for IPC payloads and JSONEncoder/Decoder over manual parsing.
Error Handling
enum WalletError: Error {
case insufficientFunds(Amount)
case invalidAddress(String)
}
func send(amount: Amount, to address: String) throws -> Transaction {
guard isValid(address) else { throw WalletError.invalidAddress(address) }
guard hasFunds(amount) else { throw WalletError.insufficientFunds(amount) }
return buildTx(amount, address)
}
// Call site
do {
let tx = try send(amount: 1000, to: "bc1q...")
print(tx)
} catch WalletError.insufficientFunds(let need) {
print("need \(need)")
} catch {
print("other error: \(error)")
}
// try? returns optional, try! force-unwraps (avoid)
let tx = try? send(amount: 1000, to: address)
Result Builders (DSLs)
Power SwiftUI's body and many Apple DSLs.
@resultBuilder
struct StringBuilder {
static func buildBlock(_ components: String...) -> String {
components.joined(separator: "\n")
}
static func bui
Установить swift в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditВложенные файлы
FAQ
Что делает скилл swift?
Swift language fundamentals (5.10+ / 6.x). Covers optionals, value vs reference semantics, protocols & generics, Swift Concurrency (async/await, actors, Sendable, structured tasks), Result Builders, and Apple platform interop. USE WHEN: user mentions "Swift", "SwiftUI", "async/await Swift", "actor", "Sendable", "Codable", "Combine", "Result Builder", "Apple Keychain", "Secure Enclave", "iOS native" DO NOT USE FOR: reviewing existing Swift code - use `review/swift`, which covers retain cycles and the concurrency checking that is a per-target setting DO NOT USE FOR: SwiftUI screen layouts in depth - use SwiftUI-specific skill if exists DO NOT USE FOR: Compose iOS via Skia - use `frontend-frameworks/compose-multiplatform` DO NOT USE FOR: Kotlin/Native ↔ Swift bridging - use `languages/uniffi`
Как установить скилл swift?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл swift запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic