Coding Best Practices Skill
Reviews Swift/iOS code for adherence to modern Swift idioms, Apple platform best practices, architecture patterns, and code quality standards.
When This Skill Activates
Use this skill when the user:
- Asks for code review or code quality check
- Mentions "best practices", "clean code", or "refactoring"
- Wants to improve existing code
- Requests architecture or design pattern review
- Asks about Swift idioms or modern patterns
- Wants performance optimization suggestions
Review Process
1. Identify Scope
- If user specifies files/classes, review those
- Otherwise, ask which areas to focus on or review recent changes
- Prioritize ViewModels, business logic, and data layer over simple views
2. Load Reference Patterns
Before starting the review, familiarize yourself with the reference patterns by reading the following files in .claude/skills/coding-best-practices/:
- swift-patterns.md - Optionals, type safety, collections, error handling, naming
- swiftui-patterns.md - State management, view composition, performance
- architecture-patterns.md - MVVM, code organization, memory management, security
- coredata-patterns.md - Core Data best practices, fetching, saving, relationships
3. Review Categories
Apply these review categories based on the code type:
For All Code:
- Swift language idioms (optionals, type safety, collections)
- Naming conventions
- Error handling
- Memory management
For SwiftUI Code:
- State management (
@State, @Observable + @Bindable; legacy @StateObject / @ObservedObject pre-iOS 17)
- View composition and performance
- MVVM separation
For ViewModels:
- Business logic placement
- MVVM architecture adherence
- Testability (dependency injection)
For Core Data Code:
- Context management
- Save/fetch patterns
- Relationship handling
- CloudKit integration
4. Review Output Format
Provide review in this structure:
✅ Strengths Found
- List well-implemented patterns
- Highlight good practices
- Acknowledge clean code sections
⚠️ Issues Found
For each issue, use this format:
Category: [Category Name]
[Priority]: [File.swift:line] - [Issue description]
// Current:
[problematic code]
// Suggested:
[improved code]
// Reason: [explanation]
Priority Levels:
- High: Will cause bugs, crashes, or serious issues
- Medium: Inefficient, hard to maintain, or non-idiomatic
- Low: Minor improvements, nice-to-haves
📊 Code Quality Score
Overall: X/10
- Swift Idioms: X/10
- Architecture: X/10
- Error Handling: X/10
- Naming: X/10
- Organization: X/10
- Performance: X/10
📋 Recommendations
- High Priority: [Critical issues]
- Medium Priority: [Improvements]
- Low Priority: [Nice-to-haves]
🔧 Quick Wins
List 3-5 easy fixes that provide immediate value
Review Checklist
Use this comprehensive checklist during review:
Swift Language
SwiftUI
Architecture
Core Data
Memory Management
Testing & Security
Modern SwiftUI Baseline (What to Reach For Today)
The default APIs to expect in a healthy SwiftUI codebase. During review, flag code still on the legacy column — each line is: reach for this / when. Version floors in parentheses; anything unmarked is broadly available.
Structure & navigation
NavigationStack / NavigationSplitView — NavigationView is deprecated; value-based links + navigationDestination (iOS 16+)
State & data flow
@Observable over ObservableObject — per-property invalidation means fewer re-renders, no @Published (iOS 17+)
@State lazily initializes @Observable classes (behavior backported to iOS 17) — delete double-initialization workarounds and "cheap placeholder default" hacks
@Previewable inside #Preview — use @State directly in a preview without a wrapper view (Xcode 16+)
Presentation & input
presentationDetents for resizable sheets — half-height/custom stops instead of full-screen covers (iOS 16+)
- Item-binding
alert(_:item:) / confirmationDialog(_:item:) — prefer over isPresented + a side-car state variable; the item carries the context (WWDC26)
searchable with scopes, tokens, and suggestions + searchFocused for programmatic search-field focus — structured search over hand-rolled filter bars
@FocusState + defaultFocus + focused(_:equals:) for focus management; onKeyPress for hardware-keyboard handling
- Spring presets
.smooth / .snappy / .bouncy — sensible spring defaults before hand-tuning stiffness/damping (iOS 17+)
Scrolling
- The scroll suite:
.scrollTargetBehavior(.paging) / .viewAligned, scrollPosition, onScrollGeometryChange / onScrollVisibilityChange — paging, position control, and scroll-driven effects without GeometryReader + preference-key plumbing (iOS 17+)
Content & media
ShareLink + Transferable — system share sheet from a declarative type conformance (iOS 16+)
PhotosPicker — out-of-process photo selection, no permission prompt (iOS 16+)
AsyncImage participates in HTTP caching by default (WWDC26); set asyncImageURLSession for custom cache/auth policies
Lists & collections
reorderable() on ForEach and swipeActions outside List — drag-reorder and swipe in lazy stacks/grids too (WWDC26)
Layout, effects & design
visualEffect over GeometryReader for visual-only geometry (scroll parallax, proximity scaling) — reads geometry without changing layout (iOS 17+)
glassEffect() + ToolbarSpacer + bottom-aligned search for the system design language (iOS 26+) — route deep Liquid Glass work to design/liquid-glass
@ContentBuilder as the ViewBuilder evolution — one builder for content usable across views, widgets, and app intents (WWDC26)
Example Review Output
Reviewing: ExpenseViewModel.swift
✅ Strengths Found
- Excellent use of @Published properties
- Clean separation between public and private methods
- Good error handling with custom error types
- Proper use of guard statements for early returns
⚠️ Issues Found
**Category: Optionals Handling**
**High Priority: ExpenseViewModel.swift:45** - Force unwrapping
// Current:
let payer = expense.payer!
// Suggested:
guard let payer = expense.payer else {
print("Expense has no payer")
return
}
// Reason: Force unwrapping will crash if payer is nil. Use guard for safe unwrapping.
**Category: Core Data**
**Medium Priority: ExpenseViewModel.swift:89** - Saving without checking hasChanges
// Current:
try? context.save()
// Suggested:
if context.hasChanges {
do {
try context.save()
} catch {
print("Failed to save: \(error.localizedDescription)")
}
}
// Reason: Check hasChanges to avoid unnecessary saves. Handle errors properly.
**Category: Collections**
**Low Priority: ExpenseViewModel.swift:123** - Inefficient filtering
// Current:
let found = expenses.filter { $0.id == targetId }.first
// Suggested:
let found = expenses.first { $0.id == targetId }
// Reason: first(where:) stops at first match, filter processes entire array.
📊 Code Quality Score
**Overall: 7/10**
- Swift Idioms: 6/10 (force unwrapping, inefficient collection usage)
- Architecture: 9/10 (excellent MVVM separation)
- Error Handling: 7/10 (using try? too often)
- Naming: 9/10 (clear, descriptive names)
- Organization: 8/10 (good marks, could improve grouping)
- Performance: 7/10 (some inefficient patterns)
📋 Recommendations
1. **High Priority**: Remove all force unwrapping (5 instances found)
2. **Medium Priority**: Improve error handling (don't swallow errors with try?)
3. **Low Priority**: Use first(where:) instead of filter().first
🔧 Quick Wins
1. Replace `expense.payer!` with safe unwrapping (ExpenseViewModel.swift:45)
2. Add hasChanges check before context.save() (ExpenseViewModel.swift:89)
3. Use first(where:) for finding items (ExpenseViewModel.swift:123)
Tips for Effective Reviews
Be Constructive
- Provide clear code examples for every issue
- Explain WHY, not just WHAT
- Be educational, not judgmental
Consider Context
- Some patterns are valid in certain scenarios
- Balance idealism with pragmatism
- Consider project constraints
Actionable Feedback
- Provide specific line numbers
- Show exact code to change
- Explain expected behavior
References
Notes
- Read the reference pattern files for detailed examples
- Focus on the most impactful improvements first
- Provide code examples for all suggested changes
- Reference exact file locations (filename.swift:lineNumber)
- Be thorough but constructive
1---
2name: coding-best-practices
3description: Reviews Swift/iOS code for adherence to modern Swift idioms, Apple platform best practices, architecture patterns, and code quality standards. Use when user mentions best practices, code review, clean code, refactoring, or wants to improve code quality.
4allowed-tools: [Read, Glob, Grep]
5last_verified: 2026-07-16
6review_by: 2027-06-22
7os_version: iOS 27 / macOS 27
8---
9
10# Coding Best Practices Skill
11
12Reviews Swift/iOS code for adherence to modern Swift idioms, Apple platform best practices, architecture patterns, and code quality standards.
13
14## When This Skill Activates
15
16Use this skill when the user:
17- Asks for code review or code quality check
18- Mentions "best practices", "clean code", or "refactoring"
19- Wants to improve existing code
20- Requests architecture or design pattern review
21- Asks about Swift idioms or modern patterns
22- Wants performance optimization suggestions
23
24## Review Process
25
26### 1. Identify Scope
27
28- If user specifies files/classes, review those
29- Otherwise, ask which areas to focus on or review recent changes
30- Prioritize ViewModels, business logic, and data layer over simple views
31
32### 2. Load Reference Patterns
33
34Before starting the review, familiarize yourself with the reference patterns by reading the following files in `.claude/skills/coding-best-practices/`:
35
36- **swift-patterns.md** - Optionals, type safety, collections, error handling, naming
37- **swiftui-patterns.md** - State management, view composition, performance
38- **architecture-patterns.md** - MVVM, code organization, memory management, security
39- **coredata-patterns.md** - Core Data best practices, fetching, saving, relationships
40
41### 3. Review Categories
42
43Apply these review categories based on the code type:
44
45**For All Code:**
46- Swift language idioms (optionals, type safety, collections)
47- Naming conventions
48- Error handling
49- Memory management
50
51**For SwiftUI Code:**
52- State management (`@State`, `@Observable` + `@Bindable`; legacy `@StateObject` / `@ObservedObject` pre-iOS 17)
53- View composition and performance
54- MVVM separation
55
56**For ViewModels:**
57- Business logic placement
58- MVVM architecture adherence
59- Testability (dependency injection)
60
61**For Core Data Code:**
62- Context management
63- Save/fetch patterns
64- Relationship handling
65- CloudKit integration
66
67### 4. Review Output Format
68
69Provide review in this structure:
70
71#### ✅ Strengths Found
72- List well-implemented patterns
73- Highlight good practices
74- Acknowledge clean code sections
75
76#### ⚠️ Issues Found
77
78For each issue, use this format:
79
80**Category: [Category Name]**
81
82**[Priority]: [File.swift:line]** - [Issue description]
83```swift
84// Current:
85[problematic code]
86
87// Suggested:
88[improved code]
89
90// Reason: [explanation]
91```
92
93**Priority Levels:**
94- **High**: Will cause bugs, crashes, or serious issues
95- **Medium**: Inefficient, hard to maintain, or non-idiomatic
96- **Low**: Minor improvements, nice-to-haves
97
98#### 📊 Code Quality Score
99
100**Overall: X/10**
101
102- Swift Idioms: X/10
103- Architecture: X/10
104- Error Handling: X/10
105- Naming: X/10
106- Organization: X/10
107- Performance: X/10
108
109#### 📋 Recommendations
110
1111. **High Priority**: [Critical issues]
1122. **Medium Priority**: [Improvements]
1133. **Low Priority**: [Nice-to-haves]
114
115#### 🔧 Quick Wins
116
117List 3-5 easy fixes that provide immediate value
118
119## Review Checklist
120
121Use this comprehensive checklist during review:
122
123### Swift Language
124- [ ] No force unwrapping unless intentional
125- [ ] Proper optional handling (guard, if let, ??)
126- [ ] Enums instead of string/int constants
127- [ ] Functional collection operations (map, filter, etc.)
128- [ ] Proper error handling (not silent try?)
129- [ ] Clear, descriptive naming
130
131### SwiftUI
132- [ ] Correct property wrapper usage
133- [ ] No ViewModels created in body
134- [ ] Views broken into components
135- [ ] No heavy computation in body
136- [ ] Single source of truth
137- [ ] Reaches for the modern baseline APIs (see Modern SwiftUI Baseline below)
138
139### Architecture
140- [ ] MVVM separation maintained
141- [ ] Business logic in ViewModels
142- [ ] UI logic in Views only
143- [ ] Proper code organization with MARK
144- [ ] Private by default
145
146### Core Data
147- [ ] Using shared context
148- [ ] hasChanges check before save
149- [ ] Typed fetch requests
150- [ ] Safe property access
151- [ ] Proper error handling
152
153### Memory Management
154- [ ] [weak self] in escaping closures
155- [ ] Weak delegates
156- [ ] No retain cycles
157
158### Testing & Security
159- [ ] Testable code structure
160- [ ] Dependency injection
161- [ ] No hardcoded secrets
162- [ ] Input validation
163- [ ] Safe logging
164
165## Modern SwiftUI Baseline (What to Reach For Today)
166
167The default APIs to expect in a healthy SwiftUI codebase. During review, flag code still on the legacy column — each line is: reach for this / when. Version floors in parentheses; anything unmarked is broadly available.
168
169**Structure & navigation**
170- `NavigationStack` / `NavigationSplitView` — `NavigationView` is deprecated; value-based links + `navigationDestination` (iOS 16+)
171
172**State & data flow**
173- `@Observable` over `ObservableObject` — per-property invalidation means fewer re-renders, no `@Published` (iOS 17+)
174- `@State` lazily initializes `@Observable` classes (behavior backported to iOS 17) — delete double-initialization workarounds and "cheap placeholder default" hacks
175- `@Previewable` inside `#Preview` — use `@State` directly in a preview without a wrapper view (Xcode 16+)
176
177**Presentation & input**
178- `presentationDetents` for resizable sheets — half-height/custom stops instead of full-screen covers (iOS 16+)
179- Item-binding `alert(_:item:)` / `confirmationDialog(_:item:)` — prefer over `isPresented` + a side-car state variable; the item carries the context (WWDC26)
180- `searchable` with scopes, tokens, and suggestions + `searchFocused` for programmatic search-field focus — structured search over hand-rolled filter bars
181- `@FocusState` + `defaultFocus` + `focused(_:equals:)` for focus management; `onKeyPress` for hardware-keyboard handling
182- Spring presets `.smooth` / `.snappy` / `.bouncy` — sensible spring defaults before hand-tuning stiffness/damping (iOS 17+)
183
184**Scrolling**
185- The scroll suite: `.scrollTargetBehavior(.paging)` / `.viewAligned`, `scrollPosition`, `onScrollGeometryChange` / `onScrollVisibilityChange` — paging, position control, and scroll-driven effects without `GeometryReader` + preference-key plumbing (iOS 17+)
186
187**Content & media**
188- `ShareLink` + `Transferable` — system share sheet from a declarative type conformance (iOS 16+)
189- `PhotosPicker` — out-of-process photo selection, no permission prompt (iOS 16+)
190- `AsyncImage` participates in HTTP caching by default (WWDC26); set `asyncImageURLSession` for custom cache/auth policies
191
192**Lists & collections**
193- `reorderable()` on `ForEach` and `swipeActions` outside `List` — drag-reorder and swipe in lazy stacks/grids too (WWDC26)
194
195**Layout, effects & design**
196- `visualEffect` over `GeometryReader` for visual-only geometry (scroll parallax, proximity scaling) — reads geometry without changing layout (iOS 17+)
197- `glassEffect()` + `ToolbarSpacer` + bottom-aligned search for the system design language (iOS 26+) — route deep Liquid Glass work to `design/liquid-glass`
198- `@ContentBuilder` as the `ViewBuilder` evolution — one builder for content usable across views, widgets, and app intents (WWDC26)
199
200## Example Review Output
201
202```
203Reviewing: ExpenseViewModel.swift
204
205✅ Strengths Found
206- Excellent use of @Published properties
207- Clean separation between public and private methods
208- Good error handling with custom error types
209- Proper use of guard statements for early returns
210
211⚠️ Issues Found
212
213**Category: Optionals Handling**
214
215**High Priority: ExpenseViewModel.swift:45** - Force unwrapping
216// Current:
217let payer = expense.payer!
218
219// Suggested:
220guard let payer = expense.payer else {
221 print("Expense has no payer")
222 return
223}
224
225// Reason: Force unwrapping will crash if payer is nil. Use guard for safe unwrapping.
226
227**Category: Core Data**
228
229**Medium Priority: ExpenseViewModel.swift:89** - Saving without checking hasChanges
230// Current:
231try? context.save()
232
233// Suggested:
234if context.hasChanges {
235 do {
236 try context.save()
237 } catch {
238 print("Failed to save: \(error.localizedDescription)")
239 }
240}
241
242// Reason: Check hasChanges to avoid unnecessary saves. Handle errors properly.
243
244**Category: Collections**
245
246**Low Priority: ExpenseViewModel.swift:123** - Inefficient filtering
247// Current:
248let found = expenses.filter { $0.id == targetId }.first
249
250// Suggested:
251let found = expenses.first { $0.id == targetId }
252
253// Reason: first(where:) stops at first match, filter processes entire array.
254
255📊 Code Quality Score
256**Overall: 7/10**
257
258- Swift Idioms: 6/10 (force unwrapping, inefficient collection usage)
259- Architecture: 9/10 (excellent MVVM separation)
260- Error Handling: 7/10 (using try? too often)
261- Naming: 9/10 (clear, descriptive names)
262- Organization: 8/10 (good marks, could improve grouping)
263- Performance: 7/10 (some inefficient patterns)
264
265📋 Recommendations
2661. **High Priority**: Remove all force unwrapping (5 instances found)
2672. **Medium Priority**: Improve error handling (don't swallow errors with try?)
2683. **Low Priority**: Use first(where:) instead of filter().first
269
270🔧 Quick Wins
2711. Replace `expense.payer!` with safe unwrapping (ExpenseViewModel.swift:45)
2722. Add hasChanges check before context.save() (ExpenseViewModel.swift:89)
2733. Use first(where:) for finding items (ExpenseViewModel.swift:123)
274```
275
276## Tips for Effective Reviews
277
278### Be Constructive
279- Provide clear code examples for every issue
280- Explain WHY, not just WHAT
281- Be educational, not judgmental
282
283### Consider Context
284- Some patterns are valid in certain scenarios
285- Balance idealism with pragmatism
286- Consider project constraints
287
288### Actionable Feedback
289- Provide specific line numbers
290- Show exact code to change
291- Explain expected behavior
292
293## References
294
295- [Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/)
296- [Swift.org Documentation](https://docs.swift.org/)
297- [SwiftUI Best Practices](https://developer.apple.com/documentation/swiftui)
298- [Core Data Programming Guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/)
299
300## Notes
301
302- Read the reference pattern files for detailed examples
303- Focus on the most impactful improvements first
304- Provide code examples for all suggested changes
305- Reference exact file locations (filename.swift:lineNumber)
306- Be thorough but constructive