Master Swift programming fundamentals - syntax, types, optionals, protocols, error handling
Provides Swift language expertise for syntax, types, optionals, protocols, and error handling. Use when writing Swift code, reviewing for safety issues, or explaining language features.
/plugin marketplace add pluginagentmarketplace/custom-plugin-swift/plugin install swift-assistant@pluginagentmarketplace-swiftThis skill inherits all available tools. When active, it can use any tool Claude has access to.
assets/Package.swift.templateassets/config.yamlreferences/GUIDE.mdreferences/PATTERNS.mdscripts/format.shscripts/lint.shComprehensive knowledge base for Swift language fundamentals, type system, and idiomatic patterns.
parameters:
swift_version:
type: string
default: "5.9"
enum: ["5.5", "5.6", "5.7", "5.8", "5.9", "5.10", "6.0"]
description: Target Swift version for compatibility
strict_concurrency:
type: boolean
default: true
description: Enable strict concurrency checking
coding_style:
type: string
enum: [apple, google, raywenderlich]
default: apple
| Topic | Description | Swift Version |
|---|---|---|
| Value Types | struct, enum, copy semantics | 5.0+ |
| Reference Types | class, ARC, identity | 5.0+ |
| Generics | Type parameters, constraints | 5.0+ |
| Opaque Types | some keyword, type erasure | 5.1+ |
| Existentials | any keyword, protocol types | 5.6+ |
| Pattern | Use Case | Example |
|---|---|---|
if let | Conditional unwrap | if let x = optional { } |
guard let | Early exit | guard let x = optional else { return } |
?? | Default value | optional ?? defaultValue |
?. | Optional chaining | object?.property?.method() |
! | Force unwrap (avoid) | Only when provably safe |
| Feature | Description |
|---|---|
| Protocol Composition | Codable & Sendable |
| Associated Types | Generic protocols with associatedtype |
| Conditional Conformance | extension Array: Equatable where Element: Equatable |
| Protocol Extensions | Default implementations |
| Pattern | Syntax | Use Case |
|---|---|---|
| Throwing | func x() throws | Recoverable errors |
| Result | Result<Success, Failure> | Async contexts |
| Optional | try? | Silent failure |
| Force | try! | Guaranteed success |
protocol Identifiable {
associatedtype ID: Hashable
var id: ID { get }
}
protocol Persistable: Identifiable {
func save() async throws
static func load(id: ID) async throws -> Self?
}
extension Persistable where Self: Codable {
func save() async throws {
let data = try JSONEncoder().encode(self)
try await Storage.shared.write(data, forKey: "\(Self.self)-\(id)")
}
}
struct UserProfile {
let name: String
let email: String?
let avatarURL: URL?
}
func displayUser(_ user: UserProfile?) {
guard let user else {
showPlaceholder()
return
}
nameLabel.text = user.name
emailLabel.text = user.email ?? "No email provided"
if let avatarURL = user.avatarURL {
loadImage(from: avatarURL)
}
}
enum ValidationError: LocalizedError {
case emptyField(String)
case invalidFormat(String, expected: String)
case outOfRange(String, min: Int, max: Int)
var errorDescription: String? {
switch self {
case .emptyField(let field):
return "\(field) cannot be empty"
case .invalidFormat(let field, let expected):
return "\(field) must be in \(expected) format"
case .outOfRange(let field, let min, let max):
return "\(field) must be between \(min) and \(max)"
}
}
}
func validate(username: String) throws -> String {
guard !username.isEmpty else {
throw ValidationError.emptyField("Username")
}
guard username.count >= 3, username.count <= 20 else {
throw ValidationError.outOfRange("Username", min: 3, max: 20)
}
return username
}
| Issue | Cause | Solution |
|---|---|---|
| "Cannot convert value of type" | Type mismatch | Check expected type, add explicit cast |
| "Value of optional type not unwrapped" | Missing unwrap | Use if let, guard let, or ?? |
| "Protocol can only be used as generic constraint" | PAT in variable | Use any or type erasure |
| "Closure captures 'self' strongly" | Retain cycle | Add [weak self] capture |
# Check Swift version
swift --version
# Compile with strict concurrency
swift build -Xswiftc -strict-concurrency=complete
# Dump AST for debugging
swiftc -dump-ast file.swift
validation:
- rule: no_force_unwrap
severity: warning
message: Avoid force unwrapping optionals
- rule: no_implicitly_unwrapped
severity: warning
message: Avoid implicitly unwrapped optionals except for IBOutlets
- rule: prefer_guard
severity: info
message: Prefer guard for early exit over nested if-let
func withRetry<T>(
maxAttempts: Int = 3,
delay: Duration = .seconds(1),
operation: () async throws -> T
) async throws -> T {
var lastError: Error?
for attempt in 1...maxAttempts {
do {
return try await operation()
} catch {
lastError = error
if attempt < maxAttempts {
try await Task.sleep(for: delay * Double(attempt))
}
}
}
throw lastError!
}
import OSLog
extension Logger {
static let swift = Logger(subsystem: "com.app", category: "swift")
}
// Usage
Logger.swift.debug("Parsing user: \(userId)")
Logger.swift.error("Failed to decode: \(error.localizedDescription)")
Skill("swift-fundamentals")
swift-spm - Package managementswift-testing - Testing fundamentals codeThis skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.