Debug SwiftUI applications systematically, covering view update failures, state management, NavigationStack issues, memory leaks, preview crashes, Combine publishers, and animation glitches with Xcode, Instruments, and LLDB techniques.
Ships in debug-and-refactor. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
A comprehensive guide for systematically debugging SwiftUI applications, covering common error patterns, debugging tools, and step-by-step resolution strategies.
Symptoms:
Root Causes:
@Published on ObservableObject propertiesSolutions:
// 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
}
Symptoms:
Solutions:
// 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)
}
}
Symptoms:
Solutions:
// 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)
Symptoms:
Solutions:
// 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)
Symptoms:
Solutions:
// 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)
}
Symptoms:
Solutions:
// 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)
Symptoms:
Solutions:
// 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()
}
}
Symptoms:
Solutions:
// 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()
}
Breakpoints:
// 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:
# 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]
Allocations:
Time Profiler:
SwiftUI Instruments (Xcode 15+):
// 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)")
// Print all environment values
struct DebugEnvironmentView: View {
@Environment(\.self) var environment
var body: some View {
let _ = print(environment)
Text("Debug")
}
}
Create minimal reproduction
Identify trigger conditions
Check iOS version specifics
Use Self._printChanges()
var body: some View {
let _ = Self._printChanges()
// Your view content
}
Add strategic breakpoints
Check property wrapper usage
Verify threading
// Check if on main thread
assert(Thread.isMainThread, "Must be on main thread")
Apply targeted fix
Test the fix
Check for side effects
Add unit tests
func testViewModelUpdatesState() async {
let viewModel = ViewModel()
await viewModel.fetchData()
XCTAssertEqual(viewModel.items.count, 10)
}
Add UI tests
func testNavigationFlow() {
let app = XCUIApplication()
app.launch()
app.buttons["DetailButton"].tap()
XCTAssertTrue(app.staticTexts["DetailView"].exists)
}
Document the fix
| Shortcut | Action |
|---|---|
| Cmd + R | Run |
| Cmd + B | Build |
| Cmd + U | Run tests |
| Cmd + Shift + K | Clean build folder |
| Cmd + Option + P | Resume preview |
| Cmd + 7 | Show debug navigator |
| Cmd + 8 | Show breakpoint navigator |
// Force view identity reset
.id(someValue)
// Track view lifecycle
.onAppear { print("View appeared") }
.onDisappear { print("View disappeared") }
.task { print("Task started") }
// Debug layout
.border(Color.red) // See frame boundaries
.background(Color.blue.opacity(0.3))
// Debug geometry
.background(GeometryReader { geo in
Color.clear.onAppear {
print("Size: \(geo.size)")
print("Frame: \(geo.frame(in: .global))")
}
})
// Debug state changes
.onChange(of: someState) { oldValue, newValue in
print("State changed from \(oldValue) to \(newValue)")
}
// In scheme > Run > Arguments > Environment Variables
OS_ACTIVITY_MODE = disable // Reduce console noise
DYLD_PRINT_STATISTICS = 1 // Print launch time stats
// Add to class to track deallocation
deinit {
print("\(Self.self) deinit")
}
// Enable Zombie Objects
// Edit Scheme > Run > Diagnostics > Zombie Objects
// Enable Address Sanitizer
// Edit Scheme > Run > Diagnostics > Address Sanitizer
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
swiftui-debugging, xcode, instruments, lldb, state-management
/debug-and-refactor:debug:swiftuifrom debug-and-refactor
npx claudepluginhub snakeo/claude-debug-and-refactor-skills-plugin --plugin debug-and-refactor45 skills in this plugin
/debug:angularDebug Angular applications systematically with expert-level diagnostic techniques. This skill provides comprehensive guidance for troubleshooting dependency injection errors, change detection issues (NG0100), RxJS subscription leaks, lazy loading failures, zone.js problems, and common Angular runtime errors. Includes structured four-phase debugging methodology, Angular DevTools usage, console debugging utilities (ng.probe), and performance profiling strategies for modern Angular applications./debug:djangoDebug Django web applications with systematic diagnostic approaches. This skill covers troubleshooting Django-specific errors including TemplateDoesNotExist, ImproperlyConfigured, IntegrityError, migration conflicts, CSRF failures, N+1 query problems, and circular imports. Includes Django Debug Toolbar setup, ORM query logging, pdb/ipdb usage, shell_plus debugging, and comprehensive logging configuration. Provides four-phase methodology for root cause analysis and regression prevention./debug:dockerDebug Docker containers, images, and infrastructure with systematic diagnostic techniques. This skill provides comprehensive guidance for troubleshooting container exit codes, OOM kills, image build failures, networking issues, volume mount problems, and permission errors. Covers four-phase debugging methodology from quick assessment to deep analysis, essential Docker commands, debug container techniques for minimal images, and platform-specific troubleshooting for Windows, Mac, and Linux.Other plugins' skills for the same job