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