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, @StateObject, @ObservedObject)
- 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
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
Prioritize Impact
- Focus on issues that affect correctness first
- Then performance and maintainability
- Style issues last
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, @StateObject, @ObservedObject)
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
134### Architecture
135- [ ] MVVM separation maintained
136- [ ] Business logic in ViewModels
137- [ ] UI logic in Views only
138- [ ] Proper code organization with MARK
139- [ ] Private by default
140
141### Core Data
142- [ ] Using shared context
143- [ ] hasChanges check before save
144- [ ] Typed fetch requests
145- [ ] Safe property access
146- [ ] Proper error handling
147
148### Memory Management
149- [ ] [weak self] in escaping closures
150- [ ] Weak delegates
151- [ ] No retain cycles
152
153### Testing & Security
154- [ ] Testable code structure
155- [ ] Dependency injection
156- [ ] No hardcoded secrets
157- [ ] Input validation
158- [ ] Safe logging
159
160## Example Review Output
161
162```
163Reviewing: ExpenseViewModel.swift
164
165✅ Strengths Found
166- Excellent use of @Published properties
167- Clean separation between public and private methods
168- Good error handling with custom error types
169- Proper use of guard statements for early returns
170
171⚠️ Issues Found
172
173**Category: Optionals Handling**
174
175**High Priority: ExpenseViewModel.swift:45** - Force unwrapping
176// Current:
177let payer = expense.payer!
178
179// Suggested:
180guard let payer = expense.payer else {
181 print("Expense has no payer")
182 return
183}
184
185// Reason: Force unwrapping will crash if payer is nil. Use guard for safe unwrapping.
186
187**Category: Core Data**
188
189**Medium Priority: ExpenseViewModel.swift:89** - Saving without checking hasChanges
190// Current:
191try? context.save()
192
193// Suggested:
194if context.hasChanges {
195 do {
196 try context.save()
197 } catch {
198 print("Failed to save: \(error.localizedDescription)")
199 }
200}
201
202// Reason: Check hasChanges to avoid unnecessary saves. Handle errors properly.
203
204**Category: Collections**
205
206**Low Priority: ExpenseViewModel.swift:123** - Inefficient filtering
207// Current:
208let found = expenses.filter { $0.id == targetId }.first
209
210// Suggested:
211let found = expenses.first { $0.id == targetId }
212
213// Reason: first(where:) stops at first match, filter processes entire array.
214
215📊 Code Quality Score
216**Overall: 7/10**
217
218- Swift Idioms: 6/10 (force unwrapping, inefficient collection usage)
219- Architecture: 9/10 (excellent MVVM separation)
220- Error Handling: 7/10 (using try? too often)
221- Naming: 9/10 (clear, descriptive names)
222- Organization: 8/10 (good marks, could improve grouping)
223- Performance: 7/10 (some inefficient patterns)
224
225📋 Recommendations
2261. **High Priority**: Remove all force unwrapping (5 instances found)
2272. **Medium Priority**: Improve error handling (don't swallow errors with try?)
2283. **Low Priority**: Use first(where:) instead of filter().first
229
230🔧 Quick Wins
2311. Replace `expense.payer!` with safe unwrapping (ExpenseViewModel.swift:45)
2322. Add hasChanges check before context.save() (ExpenseViewModel.swift:89)
2333. Use first(where:) for finding items (ExpenseViewModel.swift:123)
234```
235
236## Tips for Effective Reviews
237
238### Be Constructive
239- Provide clear code examples for every issue
240- Explain WHY, not just WHAT
241- Be educational, not judgmental
242
243### Consider Context
244- Some patterns are valid in certain scenarios
245- Balance idealism with pragmatism
246- Consider project constraints
247
248### Prioritize Impact
249- Focus on issues that affect correctness first
250- Then performance and maintainability
251- Style issues last
252
253### Actionable Feedback
254- Provide specific line numbers
255- Show exact code to change
256- Explain expected behavior
257
258## References
259
260- [Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/)
261- [Swift.org Documentation](https://docs.swift.org/)
262- [SwiftUI Best Practices](https://developer.apple.com/documentation/swiftui)
263- [Core Data Programming Guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/)
264
265## Notes
266
267- Read the reference pattern files for detailed examples
268- Focus on the most impactful improvements first
269- Provide code examples for all suggested changes
270- Reference exact file locations (filename.swift:lineNumber)
271- Be thorough but constructive