Swift Best Practices Skill
Overview
Apply modern Swift development best practices focusing on Swift 6+ features, concurrency safety, API design principles, and code quality guidelines for iOS and macOS projects targeting macOS 15.7+.
When to Use This Skill
Use this skill when:
- Writing new Swift code for iOS or macOS applications
- Reviewing Swift code for correctness, safety, and style
- Implementing Swift concurrency features (async/await, actors, MainActor)
- Designing Swift APIs and public interfaces
- Migrating code from Swift 5 to Swift 6
- Addressing concurrency warnings, data race issues, or compiler errors related to Sendable/isolation
- Working with modern Swift language features introduced in Swift 6 and 6.2
SwiftLens MCP Integration (Claude Code)
This skill complements SwiftLens MCP server for semantic-level Swift code analysis.
What SwiftLens Provides:
- 15 tools for semantic Swift analysis using Apple's SourceKit-LSP
- Symbol lookup, cross-file references, type information
- Safe code modification and refactoring
- Compiler-grade understanding of Swift code structure
What This Skill Provides:
- Swift 6+ design patterns and best practices
- Concurrency strategies (async/await, actors, MainActor)
- API design guidelines and naming conventions
- Migration guidance (Swift 5 → Swift 6)
Setup for Claude Code CLI:
Create .claude/mcps/swiftlens.json in your Swift project:
{
"mcpServers": {
"swiftlens": {
"description": "SwiftLens MCP provides semantic Swift analysis via SourceKit-LSP",
"command": "uvx",
"args": ["swiftlens"]
}
}
}
⚠️ Note: This is Claude Code configuration (not Claude Desktop). See references/swiftlens-mcp-claude-code.md for complete setup guide, all 15 tools, index building, and usage examples.
Workflow: SwiftLens provides runtime analysis (what the code is doing), this skill provides design expertise (what the code should be doing).
Core Guidelines
Fundamental Principles
- Clarity at point of use is paramount - evaluate designs by examining use cases, not just declarations
- Clarity over brevity - compact code comes from the type system, not minimal characters
- Write documentation for every public declaration - if you can't describe functionality simply, the API may be poorly designed
- Name by role, not type -
var greeting = "Hello" not var string = "Hello"
- Favour elegance through simplicity - avoid over-engineering unless complexity genuinely warrants it
Swift 6 Concurrency Model
Swift 6 enables complete concurrency checking by default with region-based isolation (SE-0414). The compiler now proves code safety, eliminating many false positives whilst catching real concurrency issues at compile time.
Critical understanding:
- Async ≠ background - async functions can suspend but don't automatically run on background threads
- Actors protect mutable shared state through automatic synchronisation
@MainActor ensures UI-related code executes on the main thread
- Global actor-isolated types are automatically
Sendable
Essential Patterns
Async/Await
// Parallel execution with async let
func fetchData() async -> (String, Int) {
async let stringData = fetchString()
async let intData = fetchInt()
return await (stringData, intData)
}
// Always check cancellation in long-running operations
func process(_ items: [Item]) async throws -> [Result] {
var results: [Result] = []
for item in items {
try Task.checkCancellation()
results.append(await process(item))
}
return results
}
MainActor for UI Code
// Apply at type level for consistent isolation
@MainActor
class ContentViewModel: ObservableObject {
@Published var images: [UIImage] = []
func fetchData() async throws {
self.images = try await fetchImages()
}
}
// Avoid MainActor.run when direct await works
await doMainActorStuff() // Good
await MainActor.run { doMainActorStuff() } // Unnecessary
Actor Isolation
actor DataCache {
private var cache: [String: Data] = [:]
func store(_ data: Data, forKey key: String) {
cache[key] = data // No await needed inside actor
}
nonisolated func cacheType() -> String {
return "DataCache" // No await needed - doesn't access isolated state
}
}
Common Pitfalls to Avoid
- Don't mark functions as
async unnecessarily - async calling convention has overhead
- Never use
DispatchSemaphore with async/await - risk of deadlock
- Don't create stateless actors - use non-isolated async functions instead
- Avoid split isolation - don't mix isolation domains within one type
- Check task cancellation - long operations must check
Task.checkCancellation()
- Don't assume async means background - explicitly move work to background if needed
- Avoid excessive context switching - group operations within same isolation domain
API Design Quick Reference
Naming Conventions
- Types/protocols:
UpperCamelCase
- Everything else:
lowerCamelCase
- Protocols describing capabilities:
-able, -ible, -ing suffixes (Equatable, ProgressReporting)
- Factory methods: Begin with
make (x.makeIterator())
- Mutating pairs: imperative vs past participle (
x.sort() / x.sorted())
Method Naming by Side Effects
- No side effects: Noun phrases (
x.distance(to: y))
- With side effects: Imperative verbs (
x.append(y), x.sort())
Argument Labels
- Omit when arguments can't be distinguished:
min(number1, number2)
- Value-preserving conversions omit first label:
Int64(someUInt32)
- Prepositional phrases label at preposition:
x.removeBoxes(havingLength: 12)
- Label all other arguments
Swift 6 Breaking Changes
Must Explicitly Mark Types with @MainActor (SE-0401)
Property wrappers no longer infer actor isolation automatically.
@MainActor
struct LogInView: View {
@StateObject private var model = ViewModel()
}
Global Variables Must Be Concurrency-Safe (SE-0412)
static let config = Config() // Constant - OK
@MainActor static var state = State() // Actor-isolated - OK
nonisolated(unsafe) var cache = [String: Data]() // Unsafe - use with caution
Other Changes
@UIApplicationMain/@NSApplicationMain deprecated (use @main)
any required for existential types
- Import visibility requires explicit access control
API Availability Patterns
// Basic availability
@available(macOS 15, iOS 18, *)
func modernAPI() { }
// Deprecation with message
@available(*, deprecated, message: "Use newMethod() instead")
func oldMethod() { }
// Renaming with auto-fix
@available(*, unavailable, renamed: "newMethod")
func oldMethod() { }
// Runtime checking
if #available(iOS 18, *) {
// iOS 18+ code
}
// Inverted checking (Swift 5.6+)
if #unavailable(iOS 18, *) {
// iOS 17 and lower
}
Key differences:
deprecated - Warning, allows usage
obsoleted - Error from specific version
unavailable - Error, completely prevents usage
How to Use This Skill
When Writing Code
- Apply naming conventions following role-based, clarity-first principles
- Use appropriate isolation (
@MainActor for UI, actors for mutable state)
- Implement async/await patterns correctly with proper cancellation handling
- Follow Swift 6 concurrency model - trust compiler's flow analysis
- Document public APIs with clear, concise summaries
When Reviewing Code
- Check for concurrency safety violations
- Verify proper actor isolation and Sendable conformance
- Ensure async functions handle cancellation appropriately
- Validate API naming follows Swift guidelines
- Confirm availability annotations are correct for target platforms
Code Quality Standards
- Minimise comments - code should be self-documenting where possible
- Avoid over-engineering and unnecessary abstractions
- Use meaningful variable names based on role, not type
- Follow established project architecture and patterns
- Prefer
count(where:) over filter().count
- Use
InlineArray for fixed-size, performance-critical data
- Trust compiler's concurrency flow analysis - avoid unnecessary
Sendable conformances
Resources
references/
Detailed reference material to load when in-depth information is needed:
- swiftlens-mcp-claude-code.md - SwiftLens MCP server setup for Claude Code CLI, 15 semantic analysis tools, index building, usage examples, and integration workflows
- api-design.md - Complete API design conventions, documentation standards, parameter guidelines, and naming patterns
- concurrency.md - Detailed async/await patterns, actor best practices, common pitfalls, performance considerations, and thread safety patterns
- swift6-features.md - New language features in Swift 6/6.2, breaking changes, migration strategies, and modern patterns
- availability-patterns.md - Comprehensive
@available attribute usage, deprecation strategies, and platform version management
Load these references when detailed information is needed beyond the core guidelines provided above.
Platform Requirements
- Swift 6.0+ compiler for Swift 6 features
- Swift 6.2+ for InlineArray and enhanced concurrency features
- macOS 15.7+ with appropriate SDK
- iOS 18+ for latest platform features
- Use
#available for runtime platform detection
- Use
@available for API availability marking
1---2name: swift-best-practices3description: |4 This skill should be used when writing or reviewing Swift code for iOS or macOS projects. Apply modern Swift 6+ best practices, concurrency patterns, API design guidelines, and migration strategies. Covers async/await, actors, MainActor, Sendable, typed throws, and Swift 6 breaking changes.56 Keywords: concurrency, async-await, actors, Sendable, typed-throws, Swift-6, migration, data-races, MainActor, nonisolated, isolated, iOS, macOS, SwiftUI, Combine, Swift-concurrency, actor-isolation, strict-concurrency, Swift-migration, modern-Swift, Swift-evolution, code-review, Swift-patterns, Apple-platforms, Xcode, iOS-development, macOS-development7license: MIT8allowed-tools: [Read, Write, Edit, Bash, Grep, Glob]9metadata:10 source: https://skillmd.com/skills/secondsky/swift-best-practices11 version: 1.0.012 swift_version: "6.0+"13 platform: "macOS 15.7+, iOS 18+"14 production_tested: true15 companion_mcp: "swiftlens"16 mcp_install: "uvx swiftlens"17 references_source: "sammcj/agentic-coding (Apache 2.0)"18---1920# Swift Best Practices Skill2122## Overview2324Apply modern Swift development best practices focusing on Swift 6+ features, concurrency safety, API design principles, and code quality guidelines for iOS and macOS projects targeting macOS 15.7+.2526## When to Use This Skill2728Use this skill when:29- Writing new Swift code for iOS or macOS applications30- Reviewing Swift code for correctness, safety, and style31- Implementing Swift concurrency features (async/await, actors, MainActor)32- Designing Swift APIs and public interfaces33- Migrating code from Swift 5 to Swift 634- Addressing concurrency warnings, data race issues, or compiler errors related to Sendable/isolation35- Working with modern Swift language features introduced in Swift 6 and 6.23637## SwiftLens MCP Integration (Claude Code)3839This skill complements **SwiftLens MCP server** for semantic-level Swift code analysis.4041**What SwiftLens Provides:**42- 15 tools for semantic Swift analysis using Apple's SourceKit-LSP43- Symbol lookup, cross-file references, type information44- Safe code modification and refactoring45- Compiler-grade understanding of Swift code structure4647**What This Skill Provides:**48- Swift 6+ design patterns and best practices49- Concurrency strategies (async/await, actors, MainActor)50- API design guidelines and naming conventions51- Migration guidance (Swift 5 → Swift 6)5253**Setup for Claude Code CLI:**5455Create `.claude/mcps/swiftlens.json` in your Swift project:5657```json58{59 "mcpServers": {60 "swiftlens": {61 "description": "SwiftLens MCP provides semantic Swift analysis via SourceKit-LSP",62 "command": "uvx",63 "args": ["swiftlens"]64 }65 }66}67```6869**⚠️ Note**: This is **Claude Code** configuration (not Claude Desktop). See `references/swiftlens-mcp-claude-code.md` for complete setup guide, all 15 tools, index building, and usage examples.7071**Workflow**: SwiftLens provides **runtime analysis** (what the code is doing), this skill provides **design expertise** (what the code should be doing).7273## Core Guidelines7475### Fundamental Principles76771. **Clarity at point of use** is paramount - evaluate designs by examining use cases, not just declarations782. **Clarity over brevity** - compact code comes from the type system, not minimal characters793. **Write documentation for every public declaration** - if you can't describe functionality simply, the API may be poorly designed804. **Name by role, not type** - `var greeting = "Hello"` not `var string = "Hello"`815. **Favour elegance through simplicity** - avoid over-engineering unless complexity genuinely warrants it8283### Swift 6 Concurrency Model8485Swift 6 enables complete concurrency checking by default with region-based isolation (SE-0414). The compiler now proves code safety, eliminating many false positives whilst catching real concurrency issues at compile time.8687**Critical understanding:**88- **Async ≠ background** - async functions can suspend but don't automatically run on background threads89- Actors protect mutable shared state through automatic synchronisation90- `@MainActor` ensures UI-related code executes on the main thread91- Global actor-isolated types are automatically `Sendable`9293### Essential Patterns9495#### Async/Await96```swift97// Parallel execution with async let98func fetchData() async -> (String, Int) {99 async let stringData = fetchString()100 async let intData = fetchInt()101 return await (stringData, intData)102}103104// Always check cancellation in long-running operations105func process(_ items: [Item]) async throws -> [Result] {106 var results: [Result] = []107 for item in items {108 try Task.checkCancellation()109 results.append(await process(item))110 }111 return results112}113```114115#### MainActor for UI Code116```swift117// Apply at type level for consistent isolation118@MainActor119class ContentViewModel: ObservableObject {120 @Published var images: [UIImage] = []121122 func fetchData() async throws {123 self.images = try await fetchImages()124 }125}126127// Avoid MainActor.run when direct await works128await doMainActorStuff() // Good129await MainActor.run { doMainActorStuff() } // Unnecessary130```131132#### Actor Isolation133```swift134actor DataCache {135 private var cache: [String: Data] = [:]136137 func store(_ data: Data, forKey key: String) {138 cache[key] = data // No await needed inside actor139 }140141 nonisolated func cacheType() -> String {142 return "DataCache" // No await needed - doesn't access isolated state143 }144}145```146147### Common Pitfalls to Avoid1481491. **Don't mark functions as `async` unnecessarily** - async calling convention has overhead1502. **Never use `DispatchSemaphore` with async/await** - risk of deadlock1513. **Don't create stateless actors** - use non-isolated async functions instead1524. **Avoid split isolation** - don't mix isolation domains within one type1535. **Check task cancellation** - long operations must check `Task.checkCancellation()`1546. **Don't assume async means background** - explicitly move work to background if needed1557. **Avoid excessive context switching** - group operations within same isolation domain156157### API Design Quick Reference158159#### Naming Conventions160- Types/protocols: `UpperCamelCase`161- Everything else: `lowerCamelCase`162- Protocols describing capabilities: `-able`, `-ible`, `-ing` suffixes (`Equatable`, `ProgressReporting`)163- Factory methods: Begin with `make` (`x.makeIterator()`)164- Mutating pairs: imperative vs past participle (`x.sort()` / `x.sorted()`)165166#### Method Naming by Side Effects167- No side effects: Noun phrases (`x.distance(to: y)`)168- With side effects: Imperative verbs (`x.append(y)`, `x.sort()`)169170#### Argument Labels171- Omit when arguments can't be distinguished: `min(number1, number2)`172- Value-preserving conversions omit first label: `Int64(someUInt32)`173- Prepositional phrases label at preposition: `x.removeBoxes(havingLength: 12)`174- Label all other arguments175176### Swift 6 Breaking Changes177178#### Must Explicitly Mark Types with @MainActor (SE-0401)179Property wrappers no longer infer actor isolation automatically.180181```swift182@MainActor183struct LogInView: View {184 @StateObject private var model = ViewModel()185}186```187188#### Global Variables Must Be Concurrency-Safe (SE-0412)189```swift190static let config = Config() // Constant - OK191@MainActor static var state = State() // Actor-isolated - OK192nonisolated(unsafe) var cache = [String: Data]() // Unsafe - use with caution193```194195#### Other Changes196- `@UIApplicationMain`/`@NSApplicationMain` deprecated (use `@main`)197- `any` required for existential types198- Import visibility requires explicit access control199200### API Availability Patterns201202```swift203// Basic availability204@available(macOS 15, iOS 18, *)205func modernAPI() { }206207// Deprecation with message208@available(*, deprecated, message: "Use newMethod() instead")209func oldMethod() { }210211// Renaming with auto-fix212@available(*, unavailable, renamed: "newMethod")213func oldMethod() { }214215// Runtime checking216if #available(iOS 18, *) {217 // iOS 18+ code218}219220// Inverted checking (Swift 5.6+)221if #unavailable(iOS 18, *) {222 // iOS 17 and lower223}224```225226**Key differences:**227- `deprecated` - Warning, allows usage228- `obsoleted` - Error from specific version229- `unavailable` - Error, completely prevents usage230231## How to Use This Skill232233### When Writing Code2342351. Apply naming conventions following role-based, clarity-first principles2362. Use appropriate isolation (`@MainActor` for UI, actors for mutable state)2373. Implement async/await patterns correctly with proper cancellation handling2384. Follow Swift 6 concurrency model - trust compiler's flow analysis2395. Document public APIs with clear, concise summaries240241### When Reviewing Code2422431. Check for concurrency safety violations2442. Verify proper actor isolation and Sendable conformance2453. Ensure async functions handle cancellation appropriately2464. Validate API naming follows Swift guidelines2475. Confirm availability annotations are correct for target platforms248249### Code Quality Standards250251- Minimise comments - code should be self-documenting where possible252- Avoid over-engineering and unnecessary abstractions253- Use meaningful variable names based on role, not type254- Follow established project architecture and patterns255- Prefer `count(where:)` over `filter().count`256- Use `InlineArray` for fixed-size, performance-critical data257- Trust compiler's concurrency flow analysis - avoid unnecessary `Sendable` conformances258259## Resources260261### references/262263Detailed reference material to load when in-depth information is needed:264265- **swiftlens-mcp-claude-code.md** - SwiftLens MCP server setup for Claude Code CLI, 15 semantic analysis tools, index building, usage examples, and integration workflows266- **api-design.md** - Complete API design conventions, documentation standards, parameter guidelines, and naming patterns267- **concurrency.md** - Detailed async/await patterns, actor best practices, common pitfalls, performance considerations, and thread safety patterns268- **swift6-features.md** - New language features in Swift 6/6.2, breaking changes, migration strategies, and modern patterns269- **availability-patterns.md** - Comprehensive `@available` attribute usage, deprecation strategies, and platform version management270271Load these references when detailed information is needed beyond the core guidelines provided above.272273## Platform Requirements274275- Swift 6.0+ compiler for Swift 6 features276- Swift 6.2+ for InlineArray and enhanced concurrency features277- macOS 15.7+ with appropriate SDK278- iOS 18+ for latest platform features279- Use `#available` for runtime platform detection280- Use `@available` for API availability marking