debug:swiftui
Debug SwiftUI application issues systematically. This skill helps diagnose and resolve SwiftUI-specific problems including view update failures, state management issues with @State/@Binding/@ObservedObject, NavigationStack problems, memory leaks from retain cycles, preview crashes, Combine publisher issues, and animation glitches. Provides Xcode debugger techniques, Instruments profiling, and LLDB commands for iOS/macOS development.
What this skill does
# SwiftUI Debugging Guide
A comprehensive guide for systematically debugging SwiftUI applications, covering common error patterns, debugging tools, and step-by-step resolution strategies.
## Common Error Patterns
### 1. View Not Updating
**Symptoms:**
- UI doesn't reflect state changes
- Data updates but view remains stale
- Animations don't trigger
**Root Causes:**
- Missing `@Published` on ObservableObject properties
- Using wrong property wrapper (@State vs @Binding vs @ObservedObject)
- Mutating state on background thread
- Object reference not triggering SwiftUI's change detection
**Solutions:**
```swift
// Ensure @Published is used for observable properties
class ViewModel: ObservableObject {
@Published var items: [Item] = [] // Correct
var count: Int = 0 // Won't trigger updates
}
// Force view refresh with id modifier
List(items) { item in
ItemRow(item: item)
}
.id(UUID()) // Forces complete rebuild
// Update state on main thread
DispatchQueue.main.async {
self.viewModel.items = newItems
}
```
### 2. @State/@Binding Issues
**Symptoms:**
- Child view changes don't propagate to parent
- State resets unexpectedly
- Two-way binding doesn't work
**Solutions:**
```swift
// Parent view
struct ParentView: View {
@State private var isOn = false
var body: some View {
ChildView(isOn: $isOn) // Pass binding with $
}
}
// Child view
struct ChildView: View {
@Binding var isOn: Bool // Use @Binding, not @State
var body: some View {
Toggle("Toggle", isOn: $isOn)
}
}
```
### 3. NavigationStack Problems
**Symptoms:**
- Navigation doesn't work
- Back button missing
- Destination view not appearing
- Deprecated NavigationView warnings
**Solutions:**
```swift
// iOS 16+ use NavigationStack
NavigationStack {
List(items) { item in
NavigationLink(value: item) {
Text(item.name)
}
}
.navigationDestination(for: Item.self) { item in
DetailView(item: item)
}
}
// For programmatic navigation
@State private var path = NavigationPath()
NavigationStack(path: $path) {
// ...
}
// Navigate programmatically
path.append(item)
```
### 4. Memory Leaks with Closures
**Symptoms:**
- Memory usage grows over time
- Deinit never called
- Retain cycles in view models
**Solutions:**
```swift
// Use [weak self] in closures
viewModel.fetchData { [weak self] result in
guard let self = self else { return }
self.handleResult(result)
}
// For Combine subscriptions, store cancellables
private var cancellables = Set<AnyCancellable>()
publisher
.sink { [weak self] value in
self?.handleValue(value)
}
.store(in: &cancellables)
```
### 5. Preview Crashes
**Symptoms:**
- Canvas shows "Preview crashed"
- "Cannot preview in this file"
- Slow or unresponsive previews
**Solutions:**
```swift
// Provide mock data for previews
#Preview {
ContentView()
.environmentObject(MockViewModel())
}
// Use @available to exclude preview-incompatible code
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.previewDevice("iPhone 15 Pro")
}
}
#endif
// Simplify preview environment
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}
```
### 6. Combine Publisher Issues
**Symptoms:**
- Publisher never emits
- Multiple subscriptions
- Memory leaks
- Values emitted on wrong thread
**Solutions:**
```swift
// Ensure receiving on main thread for UI updates
publisher
.receive(on: DispatchQueue.main)
.sink { value in
self.updateUI(value)
}
.store(in: &cancellables)
// Debug publisher chain
publisher
.print("DEBUG") // Prints all events
.handleEvents(
receiveSubscription: { _ in print("Subscribed") },
receiveOutput: { print("Output: \($0)") },
receiveCompletion: { print("Completed: \($0)") },
receiveCancel: { print("Cancelled") }
)
.sink { _ in }
.store(in: &cancellables)
```
### 7. Compiler Type-Check Errors
**Symptoms:**
- "The compiler is unable to type-check this expression in reasonable time"
- Generic error messages on wrong line
- Build times extremely slow
**Solutions:**
```swift
// Break complex views into smaller components
// BAD: Complex inline logic
var body: some View {
VStack {
if condition1 && condition2 || condition3 {
// Lots of nested views...
}
}
}
// GOOD: Extract to computed properties or subviews
var body: some View {
VStack {
conditionalContent
}
}
@ViewBuilder
private var conditionalContent: some View {
if shouldShowContent {
ContentSubview()
}
}
```
### 8. Animation Issues
**Symptoms:**
- Animations not playing
- Jerky or stuttering animations
- Wrong elements animating
**Solutions:**
```swift
// Use withAnimation for explicit control
Button("Toggle") {
withAnimation(.spring()) {
isExpanded.toggle()
}
}
// Apply animation to specific value
Rectangle()
.frame(width: isExpanded ? 200 : 100)
.animation(.easeInOut, value: isExpanded)
// Use transaction for fine-grained control
var transaction = Transaction(animation: .easeInOut)
transaction.disablesAnimations = false
withTransaction(transaction) {
isExpanded.toggle()
}
```
## Debugging Tools
### Xcode Debugger
**Breakpoints:**
```swift
// Conditional breakpoint
// Right-click breakpoint > Edit Breakpoint > Condition: items.count > 10
// Symbolic breakpoint for SwiftUI layout issues
// Debug > Breakpoints > Create Symbolic Breakpoint
// Symbol: UIViewAlertForUnsatisfiableConstraints
```
**LLDB Commands:**
```lldb
# Print view hierarchy
po view.value(forKey: "recursiveDescription")
# Print SwiftUI view
po self
# Examine memory
memory read --size 8 --format x 0x12345678
# Find retain cycles
leaks --outputGraph=/tmp/leaks.memgraph [PID]
```
### Instruments
**Allocations:**
- Track memory usage over time
- Identify objects not being deallocated
- Find retain cycles
**Time Profiler:**
- Identify slow code paths
- Find main thread blocking
- Optimize view rendering
**SwiftUI Instruments (Xcode 15+):**
- View body evaluations
- View identity tracking
- State change tracking
### Print Debugging
```swift
// Track view redraws
var body: some View {
let _ = Self._printChanges() // Prints what caused redraw
Text("Hello")
}
// Conditional debug printing
#if DEBUG
func debugPrint(_ items: Any...) {
print(items)
}
#else
func debugPrint(_ items: Any...) {}
#endif
// os_log for structured logging
import os.log
let logger = Logger(subsystem: "com.app.name", category: "networking")
logger.debug("Request started: \(url)")
logger.error("Request failed: \(error.localizedDescription)")
```
### View Hierarchy Debugger
1. Run app in simulator/device
2. Click "Debug View Hierarchy" button in Xcode
3. Use 3D view to inspect layer structure
4. Check for overlapping views, incorrect frames
### Environment Inspection
```swift
// Print all environment values
struct DebugEnvironmentView: View {
@Environment(\.self) var environment
var body: some View {
let _ = print(environment)
Text("Debug")
}
}
```
## The Four Phases (SwiftUI-Specific)
### Phase 1: Reproduce and Isolate
1. **Create minimal reproduction**
- Strip away unrelated code
- Use fresh SwiftUI project if needed
- Test in Preview vs Simulator vs Device
2. **Identify trigger conditions**
- When does the bug occur?
- What user actions trigger it?
- Is it state-dependent?
3. **Check iOS version specifics**
- Does it happen on all iOS versions?
- Is it simulator-only or device-only?
### Phase 2: Diagnose
1. **Use Self._printChanges()**
```swift
var body: some View {
let _ = Self._printChanges()
// Your view content
}
```
2. **Add strategic breakpoints**
- Body property
- State mutations
- Network callbacks
3. **Check propertyRelated in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.