Swift Expert
Core Workflow
- Architecture Analysis - Identify platform targets, dependencies, design patterns
- Design Protocols - Create protocol-first APIs with associated types
- Implement - Write type-safe code with async/await and value semantics
- Optimize - Profile with Instruments, ensure thread safety
- Test - Write comprehensive tests with XCTest and async patterns
Validation checkpoints: After step 3, run swift build to verify compilation. After step 4, run swift build -warnings-as-errors to surface actor isolation and Sendable warnings. After step 5, run swift test and confirm all async tests pass.
Reference Guide
Load detailed guidance based on context:
| Topic |
Reference |
Load When |
| SwiftUI |
references/swiftui-patterns.md |
Building views, state management, modifiers |
| Concurrency |
references/async-concurrency.md |
async/await, actors, structured concurrency |
| Protocols |
references/protocol-oriented.md |
Protocol design, generics, type erasure |
| Memory |
references/memory-performance.md |
ARC, weak/unowned, performance optimization |
| Testing |
references/testing-patterns.md |
XCTest, async tests, mocking strategies |
Code Patterns
async/await — Correct vs. Incorrect
// ✅ DO: async/await with structured error handling
func fetchUser(id: String) async throws -> User {
let url = URL(string: "https://api.example.com/users/\(id)")!
let (data, _) = try await URLSession.shared.data(from: url)
return try JSONDecoder().decode(User.self, from: data)
}
// ❌ DON'T: mixing completion handlers with async context
func fetchUser(id: String) async throws -> User {
return try await withCheckedThrowingContinuation { continuation in
// Avoid wrapping existing async APIs this way when a native async version exists
legacyFetch(id: id) { result in
continuation.resume(with: result)
}
}
}
SwiftUI State Management
// ✅ DO: use @Observable (Swift 5.9+) for view models
@Observable
final class CounterViewModel {
var count = 0
func increment() { count += 1 }
}
struct CounterView: View {
@State private var vm = CounterViewModel()
var body: some View {
VStack {
Text("\(vm.count)")
Button("Increment", action: vm.increment)
}
}
}
// ❌ DON'T: reach for ObservableObject/Published when @Observable suffices
class LegacyViewModel: ObservableObject {
@Published var count = 0 // Unnecessary boilerplate in Swift 5.9+
}
Protocol-Oriented Architecture
// ✅ DO: define capability protocols with associated types
protocol Repository<Entity> {
associatedtype Entity: Identifiable
func fetch(id: Entity.ID) async throws -> Entity
func save(_ entity: Entity) async throws
}
struct UserRepository: Repository {
typealias Entity = User
func fetch(id: UUID) async throws -> User { /* … */ }
func save(_ user: User) async throws { /* … */ }
}
// ❌ DON'T: use classes as base types when a protocol fits
class BaseRepository { // Avoid class inheritance for shared behavior
func fetch(id: UUID) async throws -> Any { fatalError("Override required") }
}
Actor for Thread Safety
// ✅ DO: isolate mutable shared state in an actor
actor ImageCache {
private var cache: [URL: UIImage] = [:]
func image(for url: URL) -> UIImage? { cache[url] }
func store(_ image: UIImage, for url: URL) { cache[url] = image }
}
// ❌ DON'T: use a class with manual locking
class UnsafeImageCache {
private var cache: [URL: UIImage] = [:]
private let lock = NSLock() // Error-prone; prefer actor isolation
func image(for url: URL) -> UIImage? {
lock.lock(); defer { lock.unlock() }
return cache[url]
}
}
Constraints
MUST DO
- Use type hints and inference appropriately
- Follow Swift API Design Guidelines
- Use
async/await for asynchronous operations (see pattern above)
- Ensure
Sendable compliance for concurrency
- Use value types (
struct/enum) by default
- Document APIs with markup comments (
/// …)
- Use property wrappers for cross-cutting concerns
- Profile with Instruments before optimizing
MUST NOT DO
- Use force unwrapping (
!) without justification
- Create retain cycles in closures
- Mix synchronous and asynchronous code improperly
- Ignore actor isolation warnings
- Use implicitly unwrapped optionals unnecessarily
- Skip error handling
- Use Objective-C patterns when Swift alternatives exist
- Hardcode platform-specific values
Output Templates
When implementing Swift features, provide:
- Protocol definitions and type aliases
- Model types (structs/classes with value semantics)
- View implementations (SwiftUI) or view controllers
- Tests demonstrating usage
- Brief explanation of architectural decisions
Documentation
1---2name: swift-expert3description: Builds iOS/macOS/watchOS/tvOS applications, implements SwiftUI views and state management, designs protocol-oriented architectures, handles async/await concurrency, implements actors for thread safety, and debugs Swift-specific issues. Use when building iOS/macOS applications with Swift 5.9+, SwiftUI, or async/await concurrency. Invoke for protocol-oriented programming, SwiftUI state management, actors, server-side Swift, UIKit integration, Combine, or Vapor.4license: MIT5compatibility: opencode6metadata:7 source: https://skillmd.com/skills/farmage/swift-expert8 author: https://github.com/Jeffallan9 version: "1.1.0"10 domain: language11 triggers: Swift, SwiftUI, iOS development, macOS development, async/await Swift, Combine, UIKit, Vapor12 role: specialist13 scope: implementation14 output-format: code15 related-skills: 16---1718# Swift Expert1920## Core Workflow21221. **Architecture Analysis** - Identify platform targets, dependencies, design patterns232. **Design Protocols** - Create protocol-first APIs with associated types243. **Implement** - Write type-safe code with async/await and value semantics254. **Optimize** - Profile with Instruments, ensure thread safety265. **Test** - Write comprehensive tests with XCTest and async patterns2728> **Validation checkpoints:** After step 3, run `swift build` to verify compilation. After step 4, run `swift build -warnings-as-errors` to surface actor isolation and Sendable warnings. After step 5, run `swift test` and confirm all async tests pass.2930## Reference Guide3132Load detailed guidance based on context:3334| Topic | Reference | Load When |35|-------|-----------|-----------|36| SwiftUI | `references/swiftui-patterns.md` | Building views, state management, modifiers |37| Concurrency | `references/async-concurrency.md` | async/await, actors, structured concurrency |38| Protocols | `references/protocol-oriented.md` | Protocol design, generics, type erasure |39| Memory | `references/memory-performance.md` | ARC, weak/unowned, performance optimization |40| Testing | `references/testing-patterns.md` | XCTest, async tests, mocking strategies |4142## Code Patterns4344### async/await — Correct vs. Incorrect4546```swift47// ✅ DO: async/await with structured error handling48func fetchUser(id: String) async throws -> User {49 let url = URL(string: "https://api.example.com/users/\(id)")!50 let (data, _) = try await URLSession.shared.data(from: url)51 return try JSONDecoder().decode(User.self, from: data)52}5354// ❌ DON'T: mixing completion handlers with async context55func fetchUser(id: String) async throws -> User {56 return try await withCheckedThrowingContinuation { continuation in57 // Avoid wrapping existing async APIs this way when a native async version exists58 legacyFetch(id: id) { result in59 continuation.resume(with: result)60 }61 }62}63```6465### SwiftUI State Management6667```swift68// ✅ DO: use @Observable (Swift 5.9+) for view models69@Observable70final class CounterViewModel {71 var count = 072 func increment() { count += 1 }73}7475struct CounterView: View {76 @State private var vm = CounterViewModel()7778 var body: some View {79 VStack {80 Text("\(vm.count)")81 Button("Increment", action: vm.increment)82 }83 }84}8586// ❌ DON'T: reach for ObservableObject/Published when @Observable suffices87class LegacyViewModel: ObservableObject {88 @Published var count = 0 // Unnecessary boilerplate in Swift 5.9+89}90```9192### Protocol-Oriented Architecture9394```swift95// ✅ DO: define capability protocols with associated types96protocol Repository<Entity> {97 associatedtype Entity: Identifiable98 func fetch(id: Entity.ID) async throws -> Entity99 func save(_ entity: Entity) async throws100}101102struct UserRepository: Repository {103 typealias Entity = User104 func fetch(id: UUID) async throws -> User { /* … */ }105 func save(_ user: User) async throws { /* … */ }106}107108// ❌ DON'T: use classes as base types when a protocol fits109class BaseRepository { // Avoid class inheritance for shared behavior110 func fetch(id: UUID) async throws -> Any { fatalError("Override required") }111}112```113114### Actor for Thread Safety115116```swift117// ✅ DO: isolate mutable shared state in an actor118actor ImageCache {119 private var cache: [URL: UIImage] = [:]120121 func image(for url: URL) -> UIImage? { cache[url] }122 func store(_ image: UIImage, for url: URL) { cache[url] = image }123}124125// ❌ DON'T: use a class with manual locking126class UnsafeImageCache {127 private var cache: [URL: UIImage] = [:]128 private let lock = NSLock() // Error-prone; prefer actor isolation129 func image(for url: URL) -> UIImage? {130 lock.lock(); defer { lock.unlock() }131 return cache[url]132 }133}134```135136## Constraints137138### MUST DO139- Use type hints and inference appropriately140- Follow Swift API Design Guidelines141- Use `async/await` for asynchronous operations (see pattern above)142- Ensure `Sendable` compliance for concurrency143- Use value types (`struct`/`enum`) by default144- Document APIs with markup comments (`/// …`)145- Use property wrappers for cross-cutting concerns146- Profile with Instruments before optimizing147148### MUST NOT DO149- Use force unwrapping (`!`) without justification150- Create retain cycles in closures151- Mix synchronous and asynchronous code improperly152- Ignore actor isolation warnings153- Use implicitly unwrapped optionals unnecessarily154- Skip error handling155- Use Objective-C patterns when Swift alternatives exist156- Hardcode platform-specific values157158## Output Templates159160When implementing Swift features, provide:1611. Protocol definitions and type aliases1622. Model types (structs/classes with value semantics)1633. View implementations (SwiftUI) or view controllers1644. Tests demonstrating usage1655. Brief explanation of architectural decisions166167[Documentation](https://jeffallan.github.io/claude-skills/skills/language/swift-expert/)