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
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:
- 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: 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.4---5
6# Swift Best Practices Skill
7
8## Overview
9
10Apply 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+.
11
12## When to Use This Skill
13
14Use this skill when:
15- Writing new Swift code for iOS or macOS applications
16- Reviewing Swift code for correctness, safety, and style
17- Implementing Swift concurrency features (async/await, actors, MainActor)
18- Designing Swift APIs and public interfaces
19- Migrating code from Swift 5 to Swift 6
20- Addressing concurrency warnings, data race issues, or compiler errors related to Sendable/isolation
21- Working with modern Swift language features introduced in Swift 6 and 6.2
22
23## Core Guidelines
24
25### Fundamental Principles
26
271. **Clarity at point of use** is paramount - evaluate designs by examining use cases, not just declarations
282. **Clarity over brevity** - compact code comes from the type system, not minimal characters
293. **Write documentation for every public declaration** - if you can't describe functionality simply, the API may be poorly designed
304. **Name by role, not type** - `var greeting = "Hello"` not `var string = "Hello"`
315. **Favour elegance through simplicity** - avoid over-engineering unless complexity genuinely warrants it
32
33### Swift 6 Concurrency Model
34
35Swift 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.
36
37**Critical understanding:**
38- **Async ≠ background** - async functions can suspend but don't automatically run on background threads
39- Actors protect mutable shared state through automatic synchronisation
40- `@MainActor` ensures UI-related code executes on the main thread
41- Global actor-isolated types are automatically `Sendable`
42
43### Essential Patterns
44
45#### Async/Await
46```swift
47// Parallel execution with async let
48func fetchData() async -> (String, Int) {
49 async let stringData = fetchString()
50 async let intData = fetchInt()
51 return await (stringData, intData)
52}
53
54// Always check cancellation in long-running operations
55func process(_ items: [Item]) async throws -> [Result] {
56 var results: [Result] = []
57 for item in items {
58 try Task.checkCancellation()
59 results.append(await process(item))
60 }
61 return results
62}
63```
64
65#### MainActor for UI Code
66```swift
67// Apply at type level for consistent isolation
68@MainActor
69class ContentViewModel: ObservableObject {
70 @Published var images: [UIImage] = []
71
72 func fetchData() async throws {
73 self.images = try await fetchImages()
74 }
75}
76
77// Avoid MainActor.run when direct await works
78await doMainActorStuff() // Good
79await MainActor.run { doMainActorStuff() } // Unnecessary
80```
81
82#### Actor Isolation
83```swift
84actor DataCache {
85 private var cache: [String: Data] = [:]
86
87 func store(_ data: Data, forKey key: String) {
88 cache[key] = data // No await needed inside actor
89 }
90
91 nonisolated func cacheType() -> String {
92 return "DataCache" // No await needed - doesn't access isolated state
93 }
94}
95```
96
97### Common Pitfalls to Avoid
98
991. **Don't mark functions as `async` unnecessarily** - async calling convention has overhead
1002. **Never use `DispatchSemaphore` with async/await** - risk of deadlock
1013. **Don't create stateless actors** - use non-isolated async functions instead
1024. **Avoid split isolation** - don't mix isolation domains within one type
1035. **Check task cancellation** - long operations must check `Task.checkCancellation()`
1046. **Don't assume async means background** - explicitly move work to background if needed
1057. **Avoid excessive context switching** - group operations within same isolation domain
106
107### API Design Quick Reference
108
109#### Naming Conventions
110- Types/protocols: `UpperCamelCase`
111- Everything else: `lowerCamelCase`
112- Protocols describing capabilities: `-able`, `-ible`, `-ing` suffixes (`Equatable`, `ProgressReporting`)
113- Factory methods: Begin with `make` (`x.makeIterator()`)
114- Mutating pairs: imperative vs past participle (`x.sort()` / `x.sorted()`)
115
116#### Method Naming by Side Effects
117- No side effects: Noun phrases (`x.distance(to: y)`)
118- With side effects: Imperative verbs (`x.append(y)`, `x.sort()`)
119
120#### Argument Labels
121- Omit when arguments can't be distinguished: `min(number1, number2)`
122- Value-preserving conversions omit first label: `Int64(someUInt32)`
123- Prepositional phrases label at preposition: `x.removeBoxes(havingLength: 12)`
124- Label all other arguments
125
126### Swift 6 Breaking Changes
127
128#### Must Explicitly Mark Types with @MainActor (SE-0401)
129Property wrappers no longer infer actor isolation automatically.
130
131```swift
132@MainActor
133struct LogInView: View {
134 @StateObject private var model = ViewModel()
135}
136```
137
138#### Global Variables Must Be Concurrency-Safe (SE-0412)
139```swift
140static let config = Config() // Constant - OK
141@MainActor static var state = State() // Actor-isolated - OK
142nonisolated(unsafe) var cache = [String: Data]() // Unsafe - use with caution
143```
144
145#### Other Changes
146- `@UIApplicationMain`/`@NSApplicationMain` deprecated (use `@main`)
147- `any` required for existential types
148- Import visibility requires explicit access control
149
150### API Availability Patterns
151
152```swift
153// Basic availability
154@available(macOS 15, iOS 18, *)
155func modernAPI() { }
156
157// Deprecation with message
158@available(*, deprecated, message: "Use newMethod() instead")
159func oldMethod() { }
160
161// Renaming with auto-fix
162@available(*, unavailable, renamed: "newMethod")
163func oldMethod() { }
164
165// Runtime checking
166if #available(iOS 18, *) {
167 // iOS 18+ code
168}
169
170// Inverted checking (Swift 5.6+)
171if #unavailable(iOS 18, *) {
172 // iOS 17 and lower
173}
174```
175
176**Key differences:**
177- `deprecated` - Warning, allows usage
178- `obsoleted` - Error from specific version
179- `unavailable` - Error, completely prevents usage
180
181## How to Use This Skill
182
183### When Writing Code
184
1851. Apply naming conventions following role-based, clarity-first principles
1862. Use appropriate isolation (`@MainActor` for UI, actors for mutable state)
1873. Implement async/await patterns correctly with proper cancellation handling
1884. Follow Swift 6 concurrency model - trust compiler's flow analysis
1895. Document public APIs with clear, concise summaries
190
191### When Reviewing Code
192
1931. Check for concurrency safety violations
1942. Verify proper actor isolation and Sendable conformance
1953. Ensure async functions handle cancellation appropriately
1964. Validate API naming follows Swift guidelines
1975. Confirm availability annotations are correct for target platforms
198
199### Code Quality Standards
200
201- Minimise comments - code should be self-documenting where possible
202- Avoid over-engineering and unnecessary abstractions
203- Use meaningful variable names based on role, not type
204- Follow established project architecture and patterns
205- Prefer `count(where:)` over `filter().count`
206- Use `InlineArray` for fixed-size, performance-critical data
207- Trust compiler's concurrency flow analysis - avoid unnecessary `Sendable` conformances
208
209## Resources
210
211### references/
212
213Detailed reference material to load when in-depth information is needed:
214
215- **api-design.md** - Complete API design conventions, documentation standards, parameter guidelines, and naming patterns
216- **concurrency.md** - Detailed async/await patterns, actor best practices, common pitfalls, performance considerations, and thread safety patterns
217- **swift6-features.md** - New language features in Swift 6/6.2, breaking changes, migration strategies, and modern patterns
218- **availability-patterns.md** - Comprehensive `@available` attribute usage, deprecation strategies, and platform version management
219
220Load these references when detailed information is needed beyond the core guidelines provided above.
221
222## Platform Requirements
223
224- Swift 6.0+ compiler for Swift 6 features
225- Swift 6.2+ for InlineArray and enhanced concurrency features
226- macOS 15.7+ with appropriate SDK
227- iOS 18+ for latest platform features
228- Use `#available` for runtime platform detection
229- Use `@available` for API availability marking