[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6E6RRKTSREDF58APCZM1SKX":3,"skill-same:01M6E6RRKTSREDF58APCZM1SKX":73},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":36,"linkOnly":37,"markdownContent":38,"markdownBody":39,"frontMatter":40,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":6,"ownerDescription":51,"updatedAt":52,"install":53,"resources":66},"01M6E6RRKTSREDF58APCZM1SKX","axiom-swiftui-debugging",null,"Use when debugging SwiftUI view updates, preview crashes, or layout issues - diagnostic decision trees to identify root causes quickly and avoid misdiagnosis under pressure","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-swiftui-debugging\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35],"axiom swiftui debugging","debugging","swiftui","use","trees","layout","self","preview","patterns","decision trees","references","performance","view","decision","ios","issues","identity","2026-11-10 10:12:30",false,"---\nname: axiom-swiftui-debugging\ndescription: Use when debugging SwiftUI view updates, preview crashes, or layout issues - diagnostic decision trees to identify root causes quickly and avoid misdiagnosis under pressure\nlicense: MIT\nmetadata:\n  version: \"1.3.0\"\n  last-updated: \"Added Self._printChanges() debugging, @Observable patterns (iOS 17+), @Bindable, view identity section, and cross-references to swiftui-performance\"\n---\n\n# SwiftUI Debugging\n\n## Overview\n\nSwiftUI debugging falls into three categories, each with a different diagnostic approach:\n\n1. **View Not Updating** – You changed something but the view didn't redraw. Decision tree to identify whether it's struct mutation, lost binding identity, accidental view recreation, or missing observer pattern.\n2. **Preview Crashes** – Your preview won't compile or crashes immediately. Decision tree to distinguish between missing dependencies, state initialization failures, and Xcode cache corruption.\n3. **Layout Issues** – Views appearing in wrong positions, wrong sizes, overlapping unexpectedly. Quick reference patterns for common scenarios.\n\n**Core principle**: Start with observable symptoms, test systematically, eliminate causes one by one. Don't guess.\n\n**Requires**: Xcode 26+, iOS 17+ (iOS 14-16 patterns still valid, see notes)\n**Related skills**: `axiom-xcode-debugging` (cache corruption diagnosis), `axiom-swift-concurrency` (observer patterns), `axiom-swiftui-performance` (profiling with Instruments), `axiom-swiftui-layout` (adaptive layout patterns)\n\n## Example Prompts\n\nThese are real questions developers ask that this skill is designed to answer:\n\n#### 1. \"My list item doesn't update when I tap the favorite button, even though the data changed\"\n→ The skill walks through the decision tree to identify struct mutation vs lost binding vs missing observer\n\n#### 2. \"Preview crashes with 'Cannot find AppModel in scope' but it compiles fine\"\n→ The skill shows how to provide missing dependencies with `.environment()` or `.environmentObject()`\n\n#### 3. \"My counter resets to 0 every time I toggle a boolean, why?\"\n→ The skill identifies accidental view recreation from conditionals and shows `.opacity()` fix\n\n#### 4. \"I'm using @Observable but the view still doesn't update when I change the property\"\n→ The skill explains when to use @State vs plain properties with @Observable objects\n\n#### 5. \"Text field loses focus when I start typing, very frustrating\"\n→ The skill identifies ForEach identity issues and shows how to use stable IDs\n\n## When to Use SwiftUI Debugging\n\n#### Use this skill when\n- ✅ A view isn't updating when you expect it to\n- ✅ Preview crashes or won't load\n- ✅ Layout looks wrong on specific devices\n- ✅ You're tempted to bandaid with @ObservedObject everywhere\n\n#### Use `axiom-xcode-debugging` instead when\n- App crashes at runtime (not preview)\n- Build fails completely\n- You need environment diagnostics\n\n#### Use `axiom-swift-concurrency` instead when\n- Questions about async\u002Fawait or MainActor\n- Data race warnings\n\n## Debugging Tools\n\n### Self._printChanges()\n\nSwiftUI provides a debug-only method to understand why a view's body was called.\n\n**Usage in LLDB**:\n```swift\n\u002F\u002F Set breakpoint in view's body\n\u002F\u002F In LLDB console:\n(lldb) expression Self._printChanges()\n```\n\n**Temporary in code** (remove before shipping):\n```swift\nvar body: some View {\n    let _ = Self._printChanges() \u002F\u002F Debug only\n\n    Text(\"Hello\")\n}\n```\n\n**Output interpretation**:\n```\nMyView: @self changed\n  - Means the view value itself changed (parameters passed to view)\n\nMyView: count changed\n  - Means @State property \"count\" triggered the update\n\nMyView: (no output)\n  - Body not being called; view not updating at all\n```\n\n**⚠️ Important**:\n- Prefixed with underscore → May be removed in future releases\n- **NEVER submit to App Store** with _printChanges calls\n- Performance impact → Use only during debugging\n\n**When to use**:\n- Need to understand exact trigger for view update\n- Investigating unexpected updates\n- Verifying dependencies after refactoring\n\n**Cross-reference**: For complex update patterns, use SwiftUI Instrument → see `axiom-swiftui-performance` skill\n\n---\n\n## View Not Updating Decision Tree\n\nThe most common frustration: you changed @State but the view didn't redraw. The root cause is always one of four things.\n\n### Step 1: Can You Reproduce in a Minimal Preview?\n\n```swift\n#Preview {\n  YourView()\n}\n```\n\n**YES** → The problem is in your code. Continue to Step 2.\n\n**NO** → It's likely Xcode state or cache corruption. Skip to Preview Crashes section.\n\n### Step 2: Diagnose the Root Cause\n\n#### Root Cause 1: Struct Mutation\n\n**Symptom**: You modify a @State value directly, but the view doesn't update.\n\n**Why it happens**: SwiftUI doesn't see direct mutations on structs. You need to reassign the entire value.\n\n```swift\n\u002F\u002F ❌ WRONG: Direct mutation doesn't trigger update\n@State var items: [String] = []\n\nfunc addItem(_ item: String) {\n    items.append(item)  \u002F\u002F SwiftUI doesn't see this change\n}\n\n\u002F\u002F ✅ RIGHT: Reassignment triggers update\n@State var items: [String] = []\n\nfunc addItem(_ item: String) {\n    var newItems = items\n    newItems.append(item)\n    self.items = newItems  \u002F\u002F Full reassignment\n}\n\n\u002F\u002F ✅ ALSO RIGHT: Use a binding\n@State var items: [String] = []\n\nvar itemsBinding: Binding\u003C[String]> {\n    Binding(\n        get: { items },\n        set: { items = $0 }\n    )\n}\n```\n\n**Fix it**: Always reassign the entire struct value, not pieces of it.\n\n---\n\n#### Root Cause 2: Lost Binding Identity\n\n**Symptom**: You pass a binding to a child view, but changes in the child don't update the parent.\n\n**Why it happens**: You're passing `.constant()` or creating a new binding each time, breaking the two-way connection.\n\n```swift\n\u002F\u002F ❌ WRONG: Constant binding is read-only\n@State var isOn = false\n\nToggleChild(value: .constant(isOn))  \u002F\u002F Changes ignored\n\n\u002F\u002F ❌ WRONG: New binding created each render\n@State var name = \"\"\n\nTextField(\"Name\", text: Binding(\n    get: { name },\n    set: { name = $0 }\n))  \u002F\u002F New binding object each time parent renders\n\n\u002F\u002F ✅ RIGHT: Pass the actual binding\n@State var isOn = false\n\nToggleChild(value: $isOn)\n\n\u002F\u002F ✅ RIGHT (iOS 17+): Use @Bindable for @Observable objects\n@Observable class Book {\n    var title = \"Sample\"\n    var isAvailable = true\n}\n\nstruct EditView: View {\n    @Bindable var book: Book  \u002F\u002F Enables $book.title syntax\n\n    var body: some View {\n        TextField(\"Title\", text: $book.title)\n        Toggle(\"Available\", isOn: $book.isAvailable)\n    }\n}\n\n\u002F\u002F ✅ ALSO RIGHT (iOS 17+): @Bindable as local variable\nstruct ListView: View {\n    @State private var books = [Book(), Book()]\n\n    var body: some View {\n        List(books) { book in\n            @Bindable var book = book  \u002F\u002F Inline binding\n            TextField(\"Title\", text: $book.title)\n        }\n    }\n}\n\n\u002F\u002F ✅ RIGHT (pre-iOS 17): Create binding once, not in body\n@State var name = \"\"\n@State var nameBinding: Binding\u003CString>?\n\nvar body: some View {\n    if nameBinding == nil {\n        nameBinding = Binding(\n            get: { name },\n            set: { name = $0 }\n        )\n    }\n    return TextField(\"Name\", text: nameBinding!)\n}\n```\n\n**Fix it**: Pass `$state` directly when possible. For @Observable objects (iOS 17+), use `@Bindable`. If creating custom bindings (pre-iOS 17), create them in `init` or cache them, not in `body`.\n\n---\n\n#### Root Cause 3: Accidental View Recreation\n\n**Symptom**: The view updates, but @State values reset to initial state. You see brief flashes of initial values.\n\n**Why it happens**: The view got a new identity (removed from a conditional, moved in a container, or the container itself was recreated), causing SwiftUI to treat it as a new view.\n\n```swift\n\u002F\u002F ❌ WRONG: View identity changes when condition flips\n@State var count = 0\n\nvar body: some View {\n    VStack {\n        if showCounter {\n            Counter()  \u002F\u002F Gets new identity each time showCounter changes\n        }\n        Button(\"Toggle\") {\n            showCounter.toggle()\n        }\n    }\n}\n\n\u002F\u002F Counter gets recreated, @State count resets to 0\n\n\u002F\u002F ✅ RIGHT: Preserve identity with opacity or hidden\n@State var count = 0\n\nvar body: some View {\n    VStack {\n        Counter()\n            .opacity(showCounter ? 1 : 0)\n        Button(\"Toggle\") {\n            showCounter.toggle()\n        }\n    }\n}\n\n\u002F\u002F ✅ ALSO RIGHT: Use id() if you must conditionally show\n@State var count = 0\n\nvar body: some View {\n    VStack {\n        if showCounter {\n            Counter()\n                .id(\"counter\")  \u002F\u002F Stable identity\n        }\n        Button(\"Toggle\") {\n            showCounter.toggle()\n        }\n    }\n}\n```\n\n**Fix it**: Preserve view identity by using `.opacity()` instead of conditionals, or apply `.id()` with a stable identifier.\n\n---\n\n#### Root Cause 4: Missing Observer Pattern\n\n**Symptom**: An object changed, but views observing it didn't update.\n\n**Why it happens**: SwiftUI doesn't know to watch for changes in the object.\n\n```swift\n\u002F\u002F ❌ WRONG: Property changes don't trigger update\nclass Model {\n    var count = 0  \u002F\u002F Not observable\n}\n\nstruct ContentView: View {\n    let model = Model()  \u002F\u002F New instance each render, not observable\n\n    var body: some View {\n        Text(\"\\(model.count)\")\n        Button(\"Increment\") {\n            model.count += 1  \u002F\u002F View doesn't update\n        }\n    }\n}\n\n\u002F\u002F ✅ RIGHT (iOS 17+): Use @Observable with @State\n@Observable class Model {\n    var count = 0  \u002F\u002F No @Published needed\n}\n\nstruct ContentView: View {\n    @State private var model = Model()  \u002F\u002F @State, not @StateObject\n\n    var body: some View {\n        Text(\"\\(model.count)\")\n        Button(\"Increment\") {\n            model.count += 1  \u002F\u002F View updates\n        }\n    }\n}\n\n\u002F\u002F ✅ RIGHT (iOS 17+): Injected @Observable objects\nstruct ContentView: View {\n    var model: Model  \u002F\u002F Just a plain property\n\n    var body: some View {\n        Text(\"\\(model.count)\")  \u002F\u002F View updates when count changes\n    }\n}\n\n\u002F\u002F ✅ RIGHT (iOS 17+): @Observable with environment\n@Observable class AppModel {\n    var count = 0\n}\n\n@main\nstruct MyApp: App {\n    @State private var model = AppModel()\n\n    var body: some Scene {\n        WindowGroup {\n            ContentView()\n                .environment(model)  \u002F\u002F Add to environment\n        }\n    }\n}\n\nstruct ContentView: View {\n    @Environment(AppModel.self) private var model  \u002F\u002F Read from environment\n\n    var body: some View {\n        Text(\"\\(model.count)\")\n    }\n}\n\n\u002F\u002F ✅ RIGHT (pre-iOS 17): Use @StateObject\u002FObservableObject\nclass Model: ObservableObject {\n    @Published var count = 0\n}\n\nstruct ContentView: View {\n    @StateObject var model = Model()  \u002F\u002F For owned instances\n\n    var body: some View {\n        Text(\"\\(model.count)\")\n        Button(\"Increment\") {\n            model.count += 1  \u002F\u002F View updates\n        }\n    }\n}\n\n\u002F\u002F ✅ RIGHT (pre-iOS 17): Use @ObservedObject for injected instances\nstruct ContentView: View {\n    @ObservedObject var model: Model  \u002F\u002F Passed in from parent\n\n    var body: some View {\n        Text(\"\\(model.count)\")\n    }\n}\n```\n\n**Fix it (iOS 17+)**: Use `@Observable` macro on your class, then `@State` to store it. Views automatically track dependencies on properties they read.\n\n**Fix it (pre-iOS 17)**: Use `@StateObject` if you own the object, `@ObservedObject` if it's injected, or `@EnvironmentObject` if it's shared across the tree.\n\n**Why @Observable is better** (iOS 17+):\n- Automatic dependency tracking (only reads trigger updates)\n- No `@Published` wrapper needed\n- Works with `@State` instead of `@StateObject`\n- Can pass as plain property instead of `@ObservedObject`\n\n**See also**: [Managing model data in your app](https:\u002F\u002Fdeveloper.apple.com\u002Fdocumentation\u002Fswiftui\u002Fmanaging-model-data-in-your-app)\n\n---\n\n### Decision Tree Summary\n\n```dot\ndigraph view_not_updating {\n    start [label=\"View not updating?\" shape=diamond];\n    reproduce [label=\"Can reproduce in preview?\" shape=diamond];\n    cause [label=\"What changed?\" shape=diamond];\n\n    start -> reproduce;\n    reproduce -> cause [label=\"yes: bug in code\"];\n    reproduce -> \"Cache\u002FXcode state → Preview Crashes\" [label=\"no\"];\n\n    cause -> \"Struct Mutation\" [label=\"modified struct directly\"];\n    cause -> \"Lost Binding Identity\" [label=\"passed binding to child\"];\n    cause -> \"Accidental Recreation\" [label=\"view inside conditional\"];\n    cause -> \"Missing Observer\" [label=\"object changed, view didn't\"];\n}\n```\n\n## Preview Crashes Decision Tree\n\nWhen your preview won't load or crashes immediately, the three root causes are distinct.\n\n### Step 1: What's the Error?\n\n#### Error Type 1: \"Cannot find in scope\" or \"No such module\"\n\n**Root cause**: Preview missing a required dependency (@EnvironmentObject, @Environment, imported module).\n\n```swift\n\u002F\u002F ❌ WRONG: ContentView needs a model, preview doesn't provide it\nstruct ContentView: View {\n    @EnvironmentObject var model: AppModel\n\n    var body: some View {\n        Text(model.title)\n    }\n}\n\n#Preview {\n    ContentView()  \u002F\u002F Crashes: model not found\n}\n\n\u002F\u002F ✅ RIGHT: Provide the dependency\n#Preview {\n    ContentView()\n        .environmentObject(AppModel())\n}\n\n\u002F\u002F ✅ ALSO RIGHT: Check for missing imports\n\u002F\u002F If using custom types, make sure they're imported in preview file\n\n#Preview {\n    MyCustomView()  \u002F\u002F Make sure MyCustomView is defined or imported\n}\n```\n\n**Fix it**: Trace the error, find what's missing, provide it to the preview.\n\n---\n\n#### Error Type 2: Fatal error or Silent crash (no error message)\n\n**Root cause**: State initialization failed at runtime. The view tried to access data that doesn't exist.\n\n```swift\n\u002F\u002F ❌ WRONG: Index out of bounds at runtime\nstruct ListView: View {\n    @State var selectedIndex = 10\n    let items = [\"a\", \"b\", \"c\"]\n\n    var body: some View {\n        Text(items[selectedIndex])  \u002F\u002F Crashes: index 10 doesn't exist\n    }\n}\n\n\u002F\u002F ❌ WRONG: Optional forced unwrap fails\nstruct DetailView: View {\n    @State var data: Data?\n\n    var body: some View {\n        Text(data!.title)  \u002F\u002F Crashes if data is nil\n    }\n}\n\n\u002F\u002F ✅ RIGHT: Safe defaults\nstruct ListView: View {\n    @State var selectedIndex = 0  \u002F\u002F Valid index\n    let items = [\"a\", \"b\", \"c\"]\n\n    var body: some View {\n        if selectedIndex \u003C items.count {\n            Text(items[selectedIndex])\n        }\n    }\n}\n\n\u002F\u002F ✅ RIGHT: Handle optionals\nstruct DetailView: View {\n    @State var data: Data?\n\n    var body: some View {\n        if let data = data {\n            Text(data.title)\n        } else {\n            Text(\"No data\")\n        }\n    }\n}\n```\n\n**Fix it**: Review your @State initializers. Check array bounds, optional unwraps, and default values.\n\n---\n\n#### Error Type 3: Works fine locally but preview won't load\n\n**Root cause**: Xcode cache corruption. The preview process has stale information about your code.\n\n**Diagnostic checklist**:\n- Preview worked yesterday, code hasn't changed → Likely cache\n- Restarting Xcode fixes it temporarily but returns → Definitely cache\n- Same code builds in simulator fine but preview fails → Cache\n- Multiple unrelated previews fail at once → Cache\n\n**Fix it** (in order):\n1. Restart Preview Canvas: `Cmd+Option+P`\n2. Restart Xcode completely (File → Close Window, then reopen project)\n3. Nuke derived data: `rm -rf ~\u002FLibrary\u002FDeveloper\u002FXcode\u002FDerivedData`\n4. Rebuild: `Cmd+B`\n\nIf still broken after all four steps: It's not cache, see Error Types 1 or 2.\n\n---\n\n### Decision Tree Summary\n\n```dot\ndigraph preview_crashes {\n    start [label=\"Preview crashes?\" shape=diamond];\n    error [label=\"Error message visible?\" shape=diamond];\n\n    start -> error;\n    error -> \"Missing Dependency\" [label=\"'Cannot find in scope'\"];\n    error -> \"State Init Failure\" [label=\"'Fatal error' or silent crash\"];\n    error -> \"Cache Corruption\" [label=\"no error\"];\n    \"Cache Corruption\" -> \"Restart Preview → Restart Xcode → Nuke DerivedData\";\n}\n```\n\n## Layout Issues Quick Reference\n\nLayout problems are usually visually obvious. Match your symptom to the pattern.\n\n### Pattern 1: Views Overlapping in ZStack\n\n**Symptom**: Views stacked on top of each other, some invisible.\n\n**Root cause**: Z-order is wrong or you're not controlling visibility.\n\n```swift\n\u002F\u002F ❌ WRONG: Can't see the blue view\nZStack {\n    Rectangle().fill(.blue)\n    Rectangle().fill(.red)\n}\n\n\u002F\u002F ✅ RIGHT: Use zIndex to control layer order\nZStack {\n    Rectangle().fill(.blue).zIndex(0)\n    Rectangle().fill(.red).zIndex(1)\n}\n\n\u002F\u002F ✅ ALSO RIGHT: Hide instead of removing from hierarchy\nZStack {\n    Rectangle().fill(.blue)\n    Rectangle().fill(.red).opacity(0.5)\n}\n```\n\n---\n\n### Pattern 2: GeometryReader Sizing Weirdness\n\n**Symptom**: View is tiny or taking up the entire screen unexpectedly.\n\n**Root cause**: GeometryReader sizes itself to available space; parent doesn't constrain it.\n\n```swift\n\u002F\u002F ❌ WRONG: GeometryReader expands to fill all available space\nVStack {\n    GeometryReader { geo in\n        Text(\"Size: \\(geo.size)\")\n    }\n    Button(\"Next\") { }\n}\n\u002F\u002F Text takes entire remaining space\n\n\u002F\u002F ✅ RIGHT: Constrain the geometry reader\nVStack {\n    GeometryReader { geo in\n        Text(\"Size: \\(geo.size)\")\n    }\n    .frame(height: 100)\n\n    Button(\"Next\") { }\n}\n```\n\n---\n\n### Pattern 3: SafeArea Complications\n\n**Symptom**: Content hidden behind notch, or not using full screen space.\n\n**Root cause**: `.ignoresSafeArea()` applied to wrong view.\n\n```swift\n\u002F\u002F ❌ WRONG: Only the background ignores safe area\nZStack {\n    Color.blue.ignoresSafeArea()\n    VStack {\n        Text(\"Still respects safe area\")\n    }\n}\n\n\u002F\u002F ✅ RIGHT: Container ignores, children position themselves\nZStack {\n    Color.blue\n    VStack {\n        Text(\"Can now use full space\")\n    }\n}\n.ignoresSafeArea()\n\n\u002F\u002F ✅ ALSO RIGHT: Be selective about which edges\nZStack {\n    Color.blue\n    VStack { ... }\n}\n.ignoresSafeArea(edges: .horizontal)  \u002F\u002F Only horizontal\n```\n\n---\n\n### Pattern 4: frame() vs fixedSize() Confusion\n\n**Symptom**: Text truncated, buttons larger than text, sizing behavior unpredictable.\n\n**Root cause**: Mixing `frame()` (constrains) with `fixedSize()` (expands to content).\n\n```swift\n\u002F\u002F ❌ WRONG: fixedSize() overrides frame()\nText(\"Long text here\")\n    .frame(width: 100)\n    .fixedSize()  \u002F\u002F Overrides the frame constraint\n\n\u002F\u002F ✅ RIGHT: Use frame() to constrain\nText(\"Long text here\")\n    .frame(width: 100, alignment: .leading)\n    .lineLimit(1)\n\n\u002F\u002F ✅ RIGHT: Use fixedSize() only for natural sizing\nVStack(spacing: 0) {\n    Text(\"Small\")\n        .fixedSize()  \u002F\u002F Sizes to text\n    Text(\"Large\")\n        .fixedSize()\n}\n```\n\n---\n\n### Pattern 5: Modifier Order Matters\n\n**Symptom**: Padding, corners, or shadows appearing in wrong place.\n\n**Root cause**: Applying modifiers in wrong order. SwiftUI applies bottom-to-top.\n\n```swift\n\u002F\u002F ❌ WRONG: Corners applied after padding\nText(\"Hello\")\n    .padding()\n    .cornerRadius(8)  \u002F\u002F Corners are too large\n\n\u002F\u002F ✅ RIGHT: Corners first, then padding\nText(\"Hello\")\n    .cornerRadius(8)\n    .padding()\n\n\u002F\u002F ❌ WRONG: Shadow after frame\nText(\"Hello\")\n    .frame(width: 100)\n    .shadow(radius: 4)  \u002F\u002F Shadow only on frame bounds\n\n\u002F\u002F ✅ RIGHT: Shadow includes all content\nText(\"Hello\")\n    .shadow(radius: 4)\n    .frame(width: 100)\n```\n\n## View Identity\n\n### Understanding View Identity\n\nSwiftUI uses view identity to track views over time, preserve state, and animate transitions. Understanding identity is critical for debugging state preservation and animation issues.\n\n### Two Types of Identity\n\n#### 1. Structural Identity (Implicit)\nPosition in view hierarchy determines identity:\n\n```swift\nVStack {\n    Text(\"First\")   \u002F\u002F Identity: VStack.child[0]\n    Text(\"Second\")  \u002F\u002F Identity: VStack.child[1]\n}\n```\n\n**When structural identity changes**:\n```swift\nif showDetails {\n    DetailView()  \u002F\u002F Identity changes when condition changes\n    SummaryView()\n} else {\n    SummaryView()  \u002F\u002F Same type, different position = different identity\n}\n```\n\n**Problem**: `SummaryView` gets recreated each time, losing @State values.\n\n#### 2. Explicit Identity\nYou control identity with `.id()` modifier:\n\n```swift\nDetailView()\n    .id(item.id)  \u002F\u002F Explicit identity tied to item\n\n\u002F\u002F When item.id changes → SwiftUI treats as different view\n\u002F\u002F → @State resets\n\u002F\u002F → Animates transition\n```\n\n### Common Identity Issues\n\n#### Issue 1: State Resets Unexpectedly\n**Symptom**: @State values reset to initial values when you don't expect.\n\n**Cause**: View identity changed (position in hierarchy or .id() value changed).\n\n```swift\n\u002F\u002F ❌ PROBLEM: Identity changes when showDetails toggles\n@State private var count = 0\n\nvar body: some View {\n    VStack {\n        if showDetails {\n            CounterView(count: $count)  \u002F\u002F Position changes\n        }\n        Button(\"Toggle\") {\n            showDetails.toggle()\n        }\n    }\n}\n\n\u002F\u002F ✅ FIX: Stable identity with .opacity()\nvar body: some View {\n    VStack {\n        CounterView(count: $count)\n            .opacity(showDetails ? 1 : 0)  \u002F\u002F Same identity always\n        Button(\"Toggle\") {\n            showDetails.toggle()\n        }\n    }\n}\n\n\u002F\u002F ✅ ALSO FIX: Explicit stable ID\nvar body: some View {\n    VStack {\n        if showDetails {\n            CounterView(count: $count)\n                .id(\"counter\")  \u002F\u002F Stable ID\n        }\n        Button(\"Toggle\") {\n            showDetails.toggle()\n        }\n    }\n}\n```\n\n#### Issue 2: Animations Don't Work\n**Symptom**: View changes but doesn't animate.\n\n**Cause**: Identity changed, SwiftUI treats as remove + add instead of update.\n\n```swift\n\u002F\u002F ❌ PROBLEM: Identity changes with selection\nForEach(items) { item in\n    ItemView(item: item)\n        .id(item.id + \"-\\(selectedID)\")  \u002F\u002F ID changes when selection changes\n}\n\n\u002F\u002F ✅ FIX: Stable identity\nForEach(items) { item in\n    ItemView(item: item, isSelected: item.id == selectedID)\n        .id(item.id)  \u002F\u002F Stable ID\n}\n```\n\n#### Issue 3: ForEach with Changing Data\n**Symptom**: List items jump around or animate incorrectly.\n\n**Cause**: Non-unique or changing identifiers.\n\n```swift\n\u002F\u002F ❌ WRONG: Index-based ID changes when array changes\nForEach(Array(items.enumerated()), id: \\.offset) { index, item in\n    Text(item.name)\n}\n\n\u002F\u002F ❌ WRONG: Non-unique IDs\nForEach(items, id: \\.category) { item in  \u002F\u002F Multiple items per category\n    Text(item.name)\n}\n\n\u002F\u002F ✅ RIGHT: Stable, unique IDs\nForEach(items, id: \\.id) { item in\n    Text(item.name)\n}\n\n\u002F\u002F ✅ RIGHT: Make type Identifiable\nstruct Item: Identifiable {\n    let id = UUID()\n    var name: String\n}\n\nForEach(items) { item in  \u002F\u002F id: \\.id implicit\n    Text(item.name)\n}\n```\n\n### When to Use .id()\n\n**Use .id() to**:\n- Force view recreation when data changes fundamentally\n- Animate transitions between distinct states\n- Reset @State when external dependency changes\n\n**Example: Force recreation on data change**:\n```swift\nDetailView(item: item)\n    .id(item.id)  \u002F\u002F New item → new view → @State resets\n```\n\n**Don't use .id() when**:\n- You just need to update view content (use bindings instead)\n- Trying to fix update issues (investigate root cause instead)\n- Identity is already stable\n\n### Debugging Identity Issues\n\n#### 1. Self._printChanges()\n```swift\nvar body: some View {\n    let _ = Self._printChanges()\n    \u002F\u002F Check if \"@self changed\" appears when you don't expect\n}\n```\n\n#### 2. Check .id() modifiers\nSearch codebase for `.id()` - are IDs changing unexpectedly?\n\n#### 3. Check conditionals\nViews in `if\u002Felse` change position → different identity.\n\n**Fix**: Use `.opacity()` or stable `.id()` instead.\n\n### Identity Quick Reference\n\n| Symptom | Likely Cause | Fix |\n|---------|--------------|-----|\n| State resets | Identity change | Use `.opacity()` instead of `if` |\n| No animation | Identity change | Remove `.id()` or use stable ID |\n| ForEach jumps | Non-unique ID | Use unique, stable IDs |\n| Unexpected recreation | Conditional position | Add explicit `.id()` |\n\n**See also**: [WWDC21: Demystify SwiftUI](https:\u002F\u002Fdeveloper.apple.com\u002Fvideos\u002Fplay\u002Fwwdc2021\u002F10022\u002F)\n\n---\n\n## Pressure Scenarios and Real-World Constraints\n\nWhen you're under deadline pressure, you'll be tempted to shortcuts that hide problems instead of fixing them.\n\n### Scenario 1: \"Preview keeps crashing, we ship tomorrow\"\n\n#### Red flags you might hear\n- \"Just rebuild everything\"\n- \"Delete derived data and don't worry about it\"\n- \"Ship without validating in preview\"\n- \"It works on my machine, good enough\"\n\n**The danger**: You skip diagnosis, cache issue recurs after 2 weeks in production, you're debugging while users hit crashes.\n\n**What to do instead** (5-minute protocol, total):\n1. Restart Preview Canvas: `Cmd+Option+P` (30 seconds)\n2. Restart Xcode (2 minutes)\n3. Nuke derived data: `rm -rf ~\u002FLibrary\u002FDeveloper\u002FXcode\u002FDerivedData` (30 seconds)\n4. Rebuild: `Cmd+B` (2 minutes)\n5. Still broken? Use the dependency or initialization decision trees above\n\n**Time cost**: 5 minutes diagnosis + 2 minutes fix = **7 minutes total**\n\n**Cost of skipping**: 30 min shipping + 24 hours debug cycle = **24+ hours total**\n\n---\n\n### Scenario 2: \"View won't update, let me just wrap it in @ObservedObject\"\n\n#### Red flags you might think\n- \"Adding @ObservedObject everywhere will fix it\"\n- \"Use ObservableObject as a band-aid\"\n- \"Add @Published to random properties\"\n- \"It's probably a binding issue, I'll just create a custom binding\"\n\n**The danger**: You're treating symptoms, not diagnosing. Same view won't update in other contexts. You've just hidden the bug.\n\n**What to do instead** (2-minute diagnosis):\n1. Can you reproduce in a minimal preview? If NO → cache corruption (see Scenario 1)\n2. If YES: Test each root cause in order:\n   - Does the view have @State that you're modifying directly? → Struct Mutation\n   - Did the view move into a conditional recently? → View Recreation\n   - Are you passing bindings to children that have changed? → Lost Binding Identity\n   - Only if none of above: Missing Observer\n3. Fix the actual root cause, not with @ObservedObject band-aid\n\n**Decision principle**: If you can't name the specific root cause, you haven't diagnosed yet. Don't code until you can answer \"the problem is struct mutation because...\".\n\n---\n\n### Scenario 2b: \"Intermittent updates - it works sometimes, not always\"\n\n#### Red flags you might think\n- \"It must be a threading issue, let me add @MainActor everywhere\"\n- \"Let me try @ObservedObject, @State, and custom Binding until something works\"\n- \"Delete DerivedData and hope cache corruption fixes it\"\n- \"This is unfixable, let me ship without this feature\"\n\n**The danger**: You're exhausted after 2 hours of guessing. You're 17 hours from App Store submission. You're panicking. Every minute feels urgent, so you stop diagnosing and start flailing.\n\nIntermittent bugs are the MOST important to diagnose correctly. One wrong guess now creates a new bug. You ship with a broken view AND a new bug. App Store rejects you. You miss launch.\n\n**What to do instead** (60-minute systematic diagnosis):\n\n**Step 1: Reproduce in preview** (15 min)\n- Create minimal preview of just the broken view\n- Tap\u002Finteract 20 times\n- Does it fail intermittently, consistently, or never?\n  - **Fails in preview**: Real bug in your code, use decision tree above\n  - **Works in preview but fails in app**: Cache or environment issue, use Preview Crashes decision tree\n  - **Can't reproduce at all**: Intermittent race condition, investigate further\n\n**Step 2: Isolate the variable** (15 min)\n- If it's intermittent in preview: Likely view recreation\n  - Did the view recently move into a conditional? Remove it and test\n  - Did you add `if` logic that might recreate the parent? Remove it and test\n- If it works in preview but fails in app: Likely environment\u002Fcache issue\n  - Try on different device\u002Fsimulator\n  - Try after clearing DerivedData\n\n**Step 3: Apply the specific fix** (30 min)\n- Once you've identified view recreation: Use `.opacity()` instead of conditionals\n- Once you've identified struct mutation: Use full reassignment\n- Once you've verified it's cache: Nuke DerivedData properly\n\n**Step 4: Verify 100% reliability** (until submission)\n- Run the same interaction 30+ times\n- Test on multiple devices\u002Fsimulators\n- Get QA to verify\n- Only ship when it's 100% reproducible (not the bug, the FIX)\n\n**Time cost**: 60 minutes diagnosis + 30 minutes fix + confidence = **submit at 9am**\n\n**Cost of guessing**: 2 hours already + 3 more hours guessing + new bug introduced + crash reports post-launch + emergency patch + reputation damage = **miss launch + post-launch chaos**\n\n**The decision principle**: Intermittent bugs require SYSTEMATIC diagnosis. The slower you go in diagnosis, the faster you get to the fix. Guessing is the fastest way to disaster.\n\n#### Professional script for co-leads who suggest guessing\n\n> \"I appreciate the suggestion. Adding @ObservedObject everywhere is treating the symptom, not the root cause. The skill says intermittent bugs create NEW bugs when we guess. I need 60 minutes for systematic diagnosis. If I can't find the root cause by then, we'll disable the feature and ship a clean v1.1. The math shows we have time—I can complete diagnosis, fix, AND verification before the deadline.\"\n\n---\n\n### Scenario 3: \"Layout looks wrong on iPad, we're out of time\"\n\n#### Red flags you might think\n- \"Add some padding and magic numbers\"\n- \"It's probably a safe area thing, let me just ignore it\"\n- \"Let's lock this to iPhone only\"\n- \"GeometryReader will solve this\"\n\n**The danger**: Magic numbers break on other sizes. SafeArea ignoring is often wrong. Locking to iPhone means you ship a broken iPad experience.\n\n**What to do instead** (3-minute diagnosis):\n1. Run in simulator or device\n2. Use Debug View Hierarchy: Debug menu → View Hierarchy (takes 30 seconds to load)\n3. Check: Is the problem SafeArea, ZStack ordering, or GeometryReader sizing?\n4. Use the correct pattern from the Quick Reference above\n\n**Time cost**: 3 minutes diagnosis + 5 minutes fix = **8 minutes total**\n\n**Cost of magic numbers**: Ship wrong, report 2 weeks later, debug 4 hours, patch in update = **2+ weeks delay**\n\n---\n\n## Quick Reference\n\n### Common View Update Fixes\n\n```swift\n\u002F\u002F Fix 1: Reassign the full struct\n@State var items: [String] = []\nvar newItems = items\nnewItems.append(\"new\")\nself.items = newItems\n\n\u002F\u002F Fix 2: Pass binding correctly\n@State var value = \"\"\nChildView(text: $value)  \u002F\u002F Pass binding, not value\n\n\u002F\u002F Fix 3: Preserve view identity\nView().opacity(isVisible ? 1 : 0)  \u002F\u002F Not: if isVisible { View() }\n\n\u002F\u002F Fix 4: Observe the object\n@StateObject var model = MyModel()\n@ObservedObject var model: MyModel\n```\n\n### Common Preview Fixes\n\n```swift\n\u002F\u002F Fix 1: Provide dependencies\n#Preview {\n    ContentView()\n        .environmentObject(AppModel())\n}\n\n\u002F\u002F Fix 2: Safe defaults\n@State var index = 0  \u002F\u002F Not 10, if array has 3 items\n\n\u002F\u002F Fix 3: Nuke cache\n\u002F\u002F Terminal: rm -rf ~\u002FLibrary\u002FDeveloper\u002FXcode\u002FDerivedData\n```\n\n### Common Layout Fixes\n\n```swift\n\u002F\u002F Fix 1: Z-order\nRectangle().zIndex(1)\n\n\u002F\u002F Fix 2: Constrain GeometryReader\nGeometryReader { geo in ... }.frame(height: 100)\n\n\u002F\u002F Fix 3: SafeArea\nZStack { ... }.ignoresSafeArea()\n\n\u002F\u002F Fix 4: Modifier order\nText().cornerRadius(8).padding()  \u002F\u002F Corners first\n```\n\n## Real-World Examples\n\n### Example 1: List Item Doesn't Update When Tapped\n\n**Scenario**: You have a list of tasks. When you tap a task to mark it complete, the checkmark should appear, but it doesn't.\n\n**Code**:\n```swift\nstruct TaskListView: View {\n    @State var tasks: [Task] = [...]\n\n    var body: some View {\n        List {\n            ForEach(tasks, id: \\.id) { task in\n                HStack {\n                    Image(systemName: task.isComplete ? \"checkmark.circle.fill\" : \"circle\")\n                    Text(task.title)\n                    Spacer()\n                    Button(\"Done\") {\n                        \u002F\u002F ❌ WRONG: Direct mutation\n                        task.isComplete.toggle()\n                    }\n                }\n            }\n        }\n    }\n}\n```\n\n**Diagnosis using the skill**:\n1. Can you reproduce in preview? YES\n2. Are you modifying the struct directly? YES → **Struct Mutation** (Root Cause 1)\n\n**Fix**:\n```swift\nButton(\"Done\") {\n    \u002F\u002F ✅ RIGHT: Full reassignment\n    if let index = tasks.firstIndex(where: { $0.id == task.id }) {\n        tasks[index].isComplete.toggle()\n    }\n}\n```\n\n**Why this works**: SwiftUI detects the array reassignment, triggering a redraw. The task in the List updates.\n\n---\n\n### Example 2: Preview Crashes with \"No Such Module\"\n\n**Scenario**: You created a custom data model. It works fine in the app, but the preview crashes with \"Cannot find 'CustomModel' in scope\".\n\n**Code**:\n```swift\nimport SwiftUI\n\n\u002F\u002F ❌ WRONG: Preview missing the dependency\n#Preview {\n    TaskDetailView(task: Task(...))\n}\n\nstruct TaskDetailView: View {\n    @Environment(\\.modelContext) var modelContext\n    let task: Task  \u002F\u002F Custom model\n\n    var body: some View {\n        Text(task.title)\n    }\n}\n```\n\n**Diagnosis using the skill**:\n1. What's the error? \"Cannot find in scope\" → **Missing Dependency** (Error Type 1)\n2. What does TaskDetailView need? The Task model and modelContext\n\n**Fix**:\n```swift\n#Preview {\n    let config = ModelConfiguration(isStoredInMemoryOnly: true)\n    let container = try! ModelContainer(for: Task.self, configurations: config)\n\n    return TaskDetailView(task: Task(title: \"Sample\"))\n        .modelContainer(container)\n}\n```\n\n**Why this works**: Providing the environment object and model container satisfies the view's dependencies. Preview loads successfully.\n\n---\n\n### Example 3: Text Field Value Changes Don't Appear\n\n**Scenario**: You have a search field. You type characters, but the text doesn't appear in the UI. However, the search results DO update.\n\n**Code**:\n```swift\nstruct SearchView: View {\n    @State var searchText = \"\"\n\n    var body: some View {\n        VStack {\n            \u002F\u002F ❌ WRONG: Passing constant binding\n            TextField(\"Search\", text: .constant(searchText))\n\n            Text(\"Results for: \\(searchText)\")  \u002F\u002F This updates\n            List {\n                ForEach(results(for: searchText), id: \\.self) { result in\n                    Text(result)\n                }\n            }\n        }\n    }\n\n    func results(for text: String) -> [String] {\n        \u002F\u002F Returns filtered results\n    }\n}\n```\n\n**Diagnosis using the skill**:\n1. Can you reproduce in preview? YES\n2. Are you passing a binding to a child view? YES (TextField)\n3. Is it a constant binding? YES → **Lost Binding Identity** (Root Cause 2)\n\n**Fix**:\n```swift\n\u002F\u002F ✅ RIGHT: Pass the actual binding\nTextField(\"Search\", text: $searchText)\n```\n\n**Why this works**: `$searchText` passes a two-way binding. TextField writes changes back to @State, triggering a redraw. Text field now shows typed characters.\n\n---\n\n## Simulator Verification\n\nAfter fixing SwiftUI issues, verify with visual confirmation in the simulator.\n\n### Why Simulator Verification Matters\n\nSwiftUI previews don't always match simulator behavior:\n- **Different rendering** — Some visual effects only work on device\u002Fsimulator\n- **Different timing** — Animations may behave differently\n- **Different state** — Full app lifecycle vs isolated preview\n\n**Use simulator verification for**:\n- Layout fixes (spacing, alignment, sizing)\n- View update fixes (state changes, bindings)\n- Animation and gesture issues\n- Before\u002Fafter visual comparison\n\n### Quick Verification Workflow\n\n```bash\n# 1. Take \"before\" screenshot\n\u002Faxiom:screenshot\n\n# 2. Apply your fix\n\n# 3. Rebuild and relaunch\nxcodebuild build -scheme YourScheme\n\n# 4. Take \"after\" screenshot\n\u002Faxiom:screenshot\n\n# 5. Compare screenshots to verify fix\n```\n\n### Navigating to Problem Screens\n\nIf the bug is deep in your app, use debug deep links to navigate directly:\n\n```bash\n# 1. Add debug deep links (see deep-link-debugging skill)\n# Example: debug:\u002F\u002Fsettings, debug:\u002F\u002Frecipe-detail?id=123\n\n# 2. Navigate and capture\nxcrun simctl openurl booted \"debug:\u002F\u002Fproblem-screen\"\nsleep 1\n\u002Faxiom:screenshot\n```\n\n### Full Simulator Testing\n\nFor complex scenarios (state setup, multiple steps, log analysis):\n\n```bash\n\u002Faxiom:test-simulator\n```\n\nThen describe what you want to test:\n- \"Navigate to the recipe editor and verify the layout fix\"\n- \"Test the profile screen with empty state\"\n- \"Verify the animation doesn't stutter anymore\"\n\n### Before\u002FAfter Example\n\n**Before fix** (view not updating):\n```bash\n# 1. Reproduce bug\nxcrun simctl openurl booted \"debug:\u002F\u002Frecipe-list\"\nsleep 1\nxcrun simctl io booted screenshot \u002Ftmp\u002Fbefore-fix.png\n# Screenshot shows: Tapping star doesn't update UI\n```\n\n**After fix** (added @State binding):\n```bash\n# 2. Test fix\nxcrun simctl openurl booted \"debug:\u002F\u002Frecipe-list\"\nsleep 1\nxcrun simctl io booted screenshot \u002Ftmp\u002Fafter-fix.png\n# Screenshot shows: Star updates immediately when tapped\n```\n\n**Time saved**: 60%+ faster iteration with visual verification vs manual navigation\n\n---\n\n## Resources\n\n**WWDC**: 2025-256, 2025-306, 2023-10160, 2023-10149, 2021-10022\n\n**Docs**: \u002Fswiftui\u002Fmanaging-model-data-in-your-app, \u002Fswiftui, \u002Fswiftui\u002Fstate-and-data-flow, \u002Fxcode\u002Fpreviews, \u002Fobservation\n\n**Skills**: axiom-swiftui-performance, axiom-swiftui-debugging-diag, axiom-xcode-debugging, axiom-swift-concurrency, axiom-lldb (LLDB debugging workflows beyond Self._printChanges)\n\n\n","# SwiftUI Debugging\n\n## Overview\n\nSwiftUI debugging falls into three categories, each with a different diagnostic approach:\n\n1. **View Not Updating** – You changed something but the view didn't redraw. Decision tree to identify whether it's struct mutation, lost binding identity, accidental view recreation, or missing observer pattern.\n2. **Preview Crashes** – Your preview won't compile or crashes immediately. Decision tree to distinguish between missing dependencies, state initialization failures, and Xcode cache corruption.\n3. **Layout Issues** – Views appearing in wrong positions, wrong sizes, overlapping unexpectedly. Quick reference patterns for common scenarios.\n\n**Core principle**: Start with observable symptoms, test systematically, eliminate causes one by one. Don't guess.\n\n**Requires**: Xcode 26+, iOS 17+ (iOS 14-16 patterns still valid, see notes)\n**Related skills**: `axiom-xcode-debugging` (cache corruption diagnosis), `axiom-swift-concurrency` (observer patterns), `axiom-swiftui-performance` (profiling with Instruments), `axiom-swiftui-layout` (adaptive layout patterns)\n\n## Example Prompts\n\nThese are real questions developers ask that this skill is designed to answer:\n\n#### 1. \"My list item doesn't update when I tap the favorite button, even though the data changed\"\n→ The skill walks through the decision tree to identify struct mutation vs lost binding vs missing observer\n\n#### 2. \"Preview crashes with 'Cannot find AppModel in scope' but it compiles fine\"\n→ The skill shows how to provide missing dependencies with `.environment()` or `.environmentObject()`\n\n#### 3. \"My counter resets to 0 every time I toggle a boolean, why?\"\n→ The skill identifies accidental view recreation from conditionals and shows `.opacity()` fix\n\n#### 4. \"I'm using @Observable but the view still doesn't update when I change the property\"\n→ The skill explains when to use @State vs plain properties with @Observable objects\n\n#### 5. \"Text field loses focus when I start typing, very frustrating\"\n→ The skill identifies ForEach identity issues and shows how to use stable IDs\n\n## When to Use SwiftUI Debugging\n\n#### Use this skill when\n- ✅ A view isn't updating when you expect it to\n- ✅ Preview crashes or won't load\n- ✅ Layout looks wrong on specific devices\n- ✅ You're tempted to bandaid with @ObservedObject everywhere\n\n#### Use `axiom-xcode-debugging` instead when\n- App crashes at runtime (not preview)\n- Build fails completely\n- You need environment diagnostics\n\n#### Use `axiom-swift-concurrency` instead when\n- Questions about async\u002Fawait or MainActor\n- Data race warnings\n\n## Debugging Tools\n\n### Self._printChanges()\n\nSwiftUI provides a debug-only method to understand why a view's body was called.\n\n**Usage in LLDB**:\n```swift\n\u002F\u002F Set breakpoint in view's body\n\u002F\u002F In LLDB console:\n(lldb) expression Self._printChanges()\n```\n\n**Temporary in code** (remove before shipping):\n```swift\nvar body: some View {\n    let _ = Self._printChanges() \u002F\u002F Debug only\n\n    Text(\"Hello\")\n}\n```\n\n**Output interpretation**:\n```\nMyView: @self changed\n  - Means the view value itself changed (parameters passed to view)\n\nMyView: count changed\n  - Means @State property \"count\" triggered the update\n\nMyView: (no output)\n  - Body not being called; view not updating at all\n```\n\n**⚠️ Important**:\n- Prefixed with underscore → May be removed in future releases\n- **NEVER submit to App Store** with _printChanges calls\n- Performance impact → Use only during debugging\n\n**When to use**:\n- Need to understand exact trigger for view update\n- Investigating unexpected updates\n- Verifying dependencies after refactoring\n\n**Cross-reference**: For complex update patterns, use SwiftUI Instrument → see `axiom-swiftui-performance` skill\n\n---\n\n## View Not Updating Decision Tree\n\nThe most common frustration: you changed @State but the view didn't redraw. The root cause is always one of four things.\n\n### Step 1: Can You Reproduce in a Minimal Preview?\n\n```swift\n#Preview {\n  YourView()\n}\n```\n\n**YES** → The problem is in your code. Continue to Step 2.\n\n**NO** → It's likely Xcode state or cache corruption. Skip to Preview Crashes section.\n\n### Step 2: Diagnose the Root Cause\n\n#### Root Cause 1: Struct Mutation\n\n**Symptom**: You modify a @State value directly, but the view doesn't update.\n\n**Why it happens**: SwiftUI doesn't see direct mutations on structs. You need to reassign the entire value.\n\n```swift\n\u002F\u002F ❌ WRONG: Direct mutation doesn't trigger update\n@State var items: [String] = []\n\nfunc addItem(_ item: String) {\n    items.append(item)  \u002F\u002F SwiftUI doesn't see this change\n}\n\n\u002F\u002F ✅ RIGHT: Reassignment triggers update\n@State var items: [String] = []\n\nfunc addItem(_ item: String) {\n    var newItems = items\n    newItems.append(item)\n    self.items = newItems  \u002F\u002F Full reassignment\n}\n\n\u002F\u002F ✅ ALSO RIGHT: Use a binding\n@State var items: [String] = []\n\nvar itemsBinding: Binding\u003C[String]> {\n    Binding(\n        get: { items },\n        set: { items = $0 }\n    )\n}\n```\n\n**Fix it**: Always reassign the entire struct value, not pieces of it.\n\n---\n\n#### Root Cause 2: Lost Binding Identity\n\n**Symptom**: You pass a binding to a child view, but changes in the child don't update the parent.\n\n**Why it happens**: You're passing `.constant()` or creating a new binding each time, breaking the two-way connection.\n\n```swift\n\u002F\u002F ❌ WRONG: Constant binding is read-only\n@State var isOn = false\n\nToggleChild(value: .constant(isOn))  \u002F\u002F Changes ignored\n\n\u002F\u002F ❌ WRONG: New binding created each render\n@State var name = \"\"\n\nTextField(\"Name\", text: Binding(\n    get: { name },\n    set: { name = $0 }\n))  \u002F\u002F New binding object each time parent renders\n\n\u002F\u002F ✅ RIGHT: Pass the actual binding\n@State var isOn = false\n\nToggleChild(value: $isOn)\n\n\u002F\u002F ✅ RIGHT (iOS 17+): Use @Bindable for @Observable objects\n@Observable class Book {\n    var title = \"Sample\"\n    var isAvailable = true\n}\n\nstruct EditView: View {\n    @Bindable var book: Book  \u002F\u002F Enables $book.title syntax\n\n    var body: some View {\n        TextField(\"Title\", text: $book.title)\n        Toggle(\"Available\", isOn: $book.isAvailable)\n    }\n}\n\n\u002F\u002F ✅ ALSO RIGHT (iOS 17+): @Bindable as local variable\nstruct ListView: View {\n    @State private var books = [Book(), Book()]\n\n    var body: some View {\n        List(books) { book in\n            @Bindable var book = book  \u002F\u002F Inline binding\n            TextField(\"Title\", text: $book.title)\n        }\n    }\n}\n\n\u002F\u002F ✅ RIGHT (pre-iOS 17): Create binding once, not in body\n@State var name = \"\"\n@State var nameBinding: Binding\u003CString>?\n\nvar body: some View {\n    if nameBinding == nil {\n        nameBinding = Binding(\n            get: { name },\n            set: { name = $0 }\n        )\n    }\n    return TextField(\"Name\", text: nameBinding!)\n}\n```\n\n**Fix it**: Pass `$state` directly when possible. For @Observable objects (iOS 17+), use `@Bindable`. If creating custom bindings (pre-iOS 17), create them in `init` or cache them, not in `body`.\n\n---\n\n#### Root Cause 3: Accidental View Recreation\n\n**Symptom**: The view updates, but @State values reset to initial state. You see brief flashes of initial values.\n\n**Why it happens**: The view got a new identity (removed from a conditional, moved in a container, or the container itself was recreated), causing SwiftUI to treat it as a new view.\n\n```swift\n\u002F\u002F ❌ WRONG: View identity changes when condition flips\n@State var count = 0\n\nvar body: some View {\n    VStack {\n        if showCounter {\n            Counter()  \u002F\u002F Gets new identity each time showCounter changes\n        }\n        Button(\"Toggle\") {\n            showCounter.toggle()\n        }\n    }\n}\n\n\u002F\u002F Counter gets recreated, @State count resets to 0\n\n\u002F\u002F ✅ RIGHT: Preserve identity with opacity or hidden\n@State var count = 0\n\nvar body: some View {\n    VStack {\n        Counter()\n            .opacity(showCounter ? 1 : 0)\n        Button(\"Toggle\") {\n            showCounter.toggle()\n        }\n    }\n}\n\n\u002F\u002F ✅ ALSO RIGHT: Use id() if you must conditionally show\n@State var count = 0\n\nvar body: some View {\n    VStack {\n        if showCounter {\n            Counter()\n                .id(\"counter\")  \u002F\u002F Stable identity\n        }\n        Button(\"Toggle\") {\n            showCounter.toggle()\n        }\n    }\n}\n```\n\n**Fix it**: Preserve view identity by using `.opacity()` instead of conditionals, or apply `.id()` with a stable identifier.\n\n---\n\n#### Root Cause 4: Missing Observer Pattern\n\n**Symptom**: An object changed, but views observing it didn't update.\n\n**Why it happens**: SwiftUI doesn't know to watch for changes in the object.\n\n```swift\n\u002F\u002F ❌ WRONG: Property changes don't trigger update\nclass Model {\n    var count = 0  \u002F\u002F Not observable\n}\n\nstruct ContentView: View {\n    let model = Model()  \u002F\u002F New instance each render, not observable\n\n    var body: some View {\n        Text(\"\\(model.count)\")\n        Button(\"Increment\") {\n            model.count += 1  \u002F\u002F View doesn't update\n        }\n    }\n}\n\n\u002F\u002F ✅ RIGHT (iOS 17+): Use @Observable with @State\n@Observable class Model {\n    var count = 0  \u002F\u002F No @Published needed\n}\n\nstruct ContentView: View {\n    @State private var model = Model()  \u002F\u002F @State, not @StateObject\n\n    var body: some View {\n        Text(\"\\(model.count)\")\n        Button(\"Increment\") {\n            model.count += 1  \u002F\u002F View updates\n        }\n    }\n}\n\n\u002F\u002F ✅ RIGHT (iOS 17+): Injected @Observable objects\nstruct ContentView: View {\n    var model: Model  \u002F\u002F Just a plain property\n\n    var body: some View {\n        Text(\"\\(model.count)\")  \u002F\u002F View updates when count changes\n    }\n}\n\n\u002F\u002F ✅ RIGHT (iOS 17+): @Observable with environment\n@Observable class AppModel {\n    var count = 0\n}\n\n@main\nstruct MyApp: App {\n    @State private var model = AppModel()\n\n    var body: some Scene {\n        WindowGroup {\n            ContentView()\n                .environment(model)  \u002F\u002F Add to environment\n        }\n    }\n}\n\nstruct ContentView: View {\n    @Environment(AppModel.self) private var model  \u002F\u002F Read from environment\n\n    var body: some View {\n        Text(\"\\(model.count)\")\n    }\n}\n\n\u002F\u002F ✅ RIGHT (pre-iOS 17): Use @StateObject\u002FObservableObject\nclass Model: ObservableObject {\n    @Published var count = 0\n}\n\nstruct ContentView: View {\n    @StateObject var model = Model()  \u002F\u002F For owned instances\n\n    var body: some View {\n        Text(\"\\(model.count)\")\n        Button(\"Increment\") {\n            model.count += 1  \u002F\u002F View updates\n        }\n    }\n}\n\n\u002F\u002F ✅ RIGHT (pre-iOS 17): Use @ObservedObject for injected instances\nstruct ContentView: View {\n    @ObservedObject var model: Model  \u002F\u002F Passed in from parent\n\n    var body: some View {\n        Text(\"\\(model.count)\")\n    }\n}\n```\n\n**Fix it (iOS 17+)**: Use `@Observable` macro on your class, then `@State` to store it. Views automatically track dependencies on properties they read.\n\n**Fix it (pre-iOS 17)**: Use `@StateObject` if you own the object, `@ObservedObject` if it's injected, or `@EnvironmentObject` if it's shared across the tree.\n\n**Why @Observable is better** (iOS 17+):\n- Automatic dependency tracking (only reads trigger updates)\n- No `@Published` wrapper needed\n- Works with `@State` instead of `@StateObject`\n- Can pass as plain property instead of `@ObservedObject`\n\n**See also**: [Managing model data in your app](https:\u002F\u002Fdeveloper.apple.com\u002Fdocumentation\u002Fswiftui\u002Fmanaging-model-data-in-your-app)\n\n---\n\n### Decision Tree Summary\n\n```dot\ndigraph view_not_updating {\n    start [label=\"View not updating?\" shape=diamond];\n    reproduce [label=\"Can reproduce in preview?\" shape=diamond];\n    cause [label=\"What changed?\" shape=diamond];\n\n    start -> reproduce;\n    reproduce -> cause [label=\"yes: bug in code\"];\n    reproduce -> \"Cache\u002FXcode state → Preview Crashes\" [label=\"no\"];\n\n    cause -> \"Struct Mutation\" [label=\"modified struct directly\"];\n    cause -> \"Lost Binding Identity\" [label=\"passed binding to child\"];\n    cause -> \"Accidental Recreation\" [label=\"view inside conditional\"];\n    cause -> \"Missing Observer\" [label=\"object changed, view didn't\"];\n}\n```\n\n## Preview Crashes Decision Tree\n\nWhen your preview won't load or crashes immediately, the three root causes are distinct.\n\n### Step 1: What's the Error?\n\n#### Error Type 1: \"Cannot find in scope\" or \"No such module\"\n\n**Root cause**: Preview missing a required dependency (@EnvironmentObject, @Environment, imported module).\n\n```swift\n\u002F\u002F ❌ WRONG: ContentView needs a model, preview doesn't provide it\nstruct ContentView: View {\n    @EnvironmentObject var model: AppModel\n\n    var body: some View {\n        Text(model.title)\n    }\n}\n\n#Preview {\n    ContentView()  \u002F\u002F Crashes: model not found\n}\n\n\u002F\u002F ✅ RIGHT: Provide the dependency\n#Preview {\n    ContentView()\n        .environmentObject(AppModel())\n}\n\n\u002F\u002F ✅ ALSO RIGHT: Check for missing imports\n\u002F\u002F If using custom types, make sure they're imported in preview file\n\n#Preview {\n    MyCustomView()  \u002F\u002F Make sure MyCustomView is defined or imported\n}\n```\n\n**Fix it**: Trace the error, find what's missing, provide it to the preview.\n\n---\n\n#### Error Type 2: Fatal error or Silent crash (no error message)\n\n**Root cause**: State initialization failed at runtime. The view tried to access data that doesn't exist.\n\n```swift\n\u002F\u002F ❌ WRONG: Index out of bounds at runtime\nstruct ListView: View {\n    @State var selectedIndex = 10\n    let items = [\"a\", \"b\", \"c\"]\n\n    var body: some View {\n        Text(items[selectedIndex])  \u002F\u002F Crashes: index 10 doesn't exist\n    }\n}\n\n\u002F\u002F ❌ WRONG: Optional forced unwrap fails\nstruct DetailView: View {\n    @State var data: Data?\n\n    var body: some View {\n        Text(data!.title)  \u002F\u002F Crashes if data is nil\n    }\n}\n\n\u002F\u002F ✅ RIGHT: Safe defaults\nstruct ListView: View {\n    @State var selectedIndex = 0  \u002F\u002F Valid index\n    let items = [\"a\", \"b\", \"c\"]\n\n    var body: some View {\n        if selectedIndex \u003C items.count {\n            Text(items[selectedIndex])\n        }\n    }\n}\n\n\u002F\u002F ✅ RIGHT: Handle optionals\nstruct DetailView: View {\n    @State var data: Data?\n\n    var body: some View {\n        if let data = data {\n            Text(data.title)\n        } else {\n            Text(\"No data\")\n        }\n    }\n}\n```\n\n**Fix it**: Review your @State initializers. Check array bounds, optional unwraps, and default values.\n\n---\n\n#### Error Type 3: Works fine locally but preview won't load\n\n**Root cause**: Xcode cache corruption. The preview process has stale information about your code.\n\n**Diagnostic checklist**:\n- Preview worked yesterday, code hasn't changed → Likely cache\n- Restarting Xcode fixes it temporarily but returns → Definitely cache\n- Same code builds in simulator fine but preview fails → Cache\n- Multiple unrelated previews fail at once → Cache\n\n**Fix it** (in order):\n1. Restart Preview Canvas: `Cmd+Option+P`\n2. Restart Xcode completely (File → Close Window, then reopen project)\n3. Nuke derived data: `rm -rf ~\u002FLibrary\u002FDeveloper\u002FXcode\u002FDerivedData`\n4. Rebuild: `Cmd+B`\n\nIf still broken after all four steps: It's not cache, see Error Types 1 or 2.\n\n---\n\n### Decision Tree Summary\n\n```dot\ndigraph preview_crashes {\n    start [label=\"Preview crashes?\" shape=diamond];\n    error [label=\"Error message visible?\" shape=diamond];\n\n    start -> error;\n    error -> \"Missing Dependency\" [label=\"'Cannot find in scope'\"];\n    error -> \"State Init Failure\" [label=\"'Fatal error' or silent crash\"];\n    error -> \"Cache Corruption\" [label=\"no error\"];\n    \"Cache Corruption\" -> \"Restart Preview → Restart Xcode → Nuke DerivedData\";\n}\n```\n\n## Layout Issues Quick Reference\n\nLayout problems are usually visually obvious. Match your symptom to the pattern.\n\n### Pattern 1: Views Overlapping in ZStack\n\n**Symptom**: Views stacked on top of each other, some invisible.\n\n**Root cause**: Z-order is wrong or you're not controlling visibility.\n\n```swift\n\u002F\u002F ❌ WRONG: Can't see the blue view\nZStack {\n    Rectangle().fill(.blue)\n    Rectangle().fill(.red)\n}\n\n\u002F\u002F ✅ RIGHT: Use zIndex to control layer order\nZStack {\n    Rectangle().fill(.blue).zIndex(0)\n    Rectangle().fill(.red).zIndex(1)\n}\n\n\u002F\u002F ✅ ALSO RIGHT: Hide instead of removing from hierarchy\nZStack {\n    Rectangle().fill(.blue)\n    Rectangle().fill(.red).opacity(0.5)\n}\n```\n\n---\n\n### Pattern 2: GeometryReader Sizing Weirdness\n\n**Symptom**: View is tiny or taking up the entire screen unexpectedly.\n\n**Root cause**: GeometryReader sizes itself to available space; parent doesn't constrain it.\n\n```swift\n\u002F\u002F ❌ WRONG: GeometryReader expands to fill all available space\nVStack {\n    GeometryReader { geo in\n        Text(\"Size: \\(geo.size)\")\n    }\n    Button(\"Next\") { }\n}\n\u002F\u002F Text takes entire remaining space\n\n\u002F\u002F ✅ RIGHT: Constrain the geometry reader\nVStack {\n    GeometryReader { geo in\n        Text(\"Size: \\(geo.size)\")\n    }\n    .frame(height: 100)\n\n    Button(\"Next\") { }\n}\n```\n\n---\n\n### Pattern 3: SafeArea Complications\n\n**Symptom**: Content hidden behind notch, or not using full screen space.\n\n**Root cause**: `.ignoresSafeArea()` applied to wrong view.\n\n```swift\n\u002F\u002F ❌ WRONG: Only the background ignores safe area\nZStack {\n    Color.blue.ignoresSafeArea()\n    VStack {\n        Text(\"Still respects safe area\")\n    }\n}\n\n\u002F\u002F ✅ RIGHT: Container ignores, children position themselves\nZStack {\n    Color.blue\n    VStack {\n        Text(\"Can now use full space\")\n    }\n}\n.ignoresSafeArea()\n\n\u002F\u002F ✅ ALSO RIGHT: Be selective about which edges\nZStack {\n    Color.blue\n    VStack { ... }\n}\n.ignoresSafeArea(edges: .horizontal)  \u002F\u002F Only horizontal\n```\n\n---\n\n### Pattern 4: frame() vs fixedSize() Confusion\n\n**Symptom**: Text truncated, buttons larger than text, sizing behavior unpredictable.\n\n**Root cause**: Mixing `frame()` (constrains) with `fixedSize()` (expands to content).\n\n```swift\n\u002F\u002F ❌ WRONG: fixedSize() overrides frame()\nText(\"Long text here\")\n    .frame(width: 100)\n    .fixedSize()  \u002F\u002F Overrides the frame constraint\n\n\u002F\u002F ✅ RIGHT: Use frame() to constrain\nText(\"Long text here\")\n    .frame(width: 100, alignment: .leading)\n    .lineLimit(1)\n\n\u002F\u002F ✅ RIGHT: Use fixedSize() only for natural sizing\nVStack(spacing: 0) {\n    Text(\"Small\")\n        .fixedSize()  \u002F\u002F Sizes to text\n    Text(\"Large\")\n        .fixedSize()\n}\n```\n\n---\n\n### Pattern 5: Modifier Order Matters\n\n**Symptom**: Padding, corners, or shadows appearing in wrong place.\n\n**Root cause**: Applying modifiers in wrong order. SwiftUI applies bottom-to-top.\n\n```swift\n\u002F\u002F ❌ WRONG: Corners applied after padding\nText(\"Hello\")\n    .padding()\n    .cornerRadius(8)  \u002F\u002F Corners are too large\n\n\u002F\u002F ✅ RIGHT: Corners first, then padding\nText(\"Hello\")\n    .cornerRadius(8)\n    .padding()\n\n\u002F\u002F ❌ WRONG: Shadow after frame\nText(\"Hello\")\n    .frame(width: 100)\n    .shadow(radius: 4)  \u002F\u002F Shadow only on frame bounds\n\n\u002F\u002F ✅ RIGHT: Shadow includes all content\nText(\"Hello\")\n    .shadow(radius: 4)\n    .frame(width: 100)\n```\n\n## View Identity\n\n### Understanding View Identity\n\nSwiftUI uses view identity to track views over time, preserve state, and animate transitions. Understanding identity is critical for debugging state preservation and animation issues.\n\n### Two Types of Identity\n\n#### 1. Structural Identity (Implicit)\nPosition in view hierarchy determines identity:\n\n```swift\nVStack {\n    Text(\"First\")   \u002F\u002F Identity: VStack.child[0]\n    Text(\"Second\")  \u002F\u002F Identity: VStack.child[1]\n}\n```\n\n**When structural identity changes**:\n```swift\nif showDetails {\n    DetailView()  \u002F\u002F Identity changes when condition changes\n    SummaryView()\n} else {\n    SummaryView()  \u002F\u002F Same type, different position = different identity\n}\n```\n\n**Problem**: `SummaryView` gets recreated each time, losing @State values.\n\n#### 2. Explicit Identity\nYou control identity with `.id()` modifier:\n\n```swift\nDetailView()\n    .id(item.id)  \u002F\u002F Explicit identity tied to item\n\n\u002F\u002F When item.id changes → SwiftUI treats as different view\n\u002F\u002F → @State resets\n\u002F\u002F → Animates transition\n```\n\n### Common Identity Issues\n\n#### Issue 1: State Resets Unexpectedly\n**Symptom**: @State values reset to initial values when you don't expect.\n\n**Cause**: View identity changed (position in hierarchy or .id() value changed).\n\n```swift\n\u002F\u002F ❌ PROBLEM: Identity changes when showDetails toggles\n@State private var count = 0\n\nvar body: some View {\n    VStack {\n        if showDetails {\n            CounterView(count: $count)  \u002F\u002F Position changes\n        }\n        Button(\"Toggle\") {\n            showDetails.toggle()\n        }\n    }\n}\n\n\u002F\u002F ✅ FIX: Stable identity with .opacity()\nvar body: some View {\n    VStack {\n        CounterView(count: $count)\n            .opacity(showDetails ? 1 : 0)  \u002F\u002F Same identity always\n        Button(\"Toggle\") {\n            showDetails.toggle()\n        }\n    }\n}\n\n\u002F\u002F ✅ ALSO FIX: Explicit stable ID\nvar body: some View {\n    VStack {\n        if showDetails {\n            CounterView(count: $count)\n                .id(\"counter\")  \u002F\u002F Stable ID\n        }\n        Button(\"Toggle\") {\n            showDetails.toggle()\n        }\n    }\n}\n```\n\n#### Issue 2: Animations Don't Work\n**Symptom**: View changes but doesn't animate.\n\n**Cause**: Identity changed, SwiftUI treats as remove + add instead of update.\n\n```swift\n\u002F\u002F ❌ PROBLEM: Identity changes with selection\nForEach(items) { item in\n    ItemView(item: item)\n        .id(item.id + \"-\\(selectedID)\")  \u002F\u002F ID changes when selection changes\n}\n\n\u002F\u002F ✅ FIX: Stable identity\nForEach(items) { item in\n    ItemView(item: item, isSelected: item.id == selectedID)\n        .id(item.id)  \u002F\u002F Stable ID\n}\n```\n\n#### Issue 3: ForEach with Changing Data\n**Symptom**: List items jump around or animate incorrectly.\n\n**Cause**: Non-unique or changing identifiers.\n\n```swift\n\u002F\u002F ❌ WRONG: Index-based ID changes when array changes\nForEach(Array(items.enumerated()), id: \\.offset) { index, item in\n    Text(item.name)\n}\n\n\u002F\u002F ❌ WRONG: Non-unique IDs\nForEach(items, id: \\.category) { item in  \u002F\u002F Multiple items per category\n    Text(item.name)\n}\n\n\u002F\u002F ✅ RIGHT: Stable, unique IDs\nForEach(items, id: \\.id) { item in\n    Text(item.name)\n}\n\n\u002F\u002F ✅ RIGHT: Make type Identifiable\nstruct Item: Identifiable {\n    let id = UUID()\n    var name: String\n}\n\nForEach(items) { item in  \u002F\u002F id: \\.id implicit\n    Text(item.name)\n}\n```\n\n### When to Use .id()\n\n**Use .id() to**:\n- Force view recreation when data changes fundamentally\n- Animate transitions between distinct states\n- Reset @State when external dependency changes\n\n**Example: Force recreation on data change**:\n```swift\nDetailView(item: item)\n    .id(item.id)  \u002F\u002F New item → new view → @State resets\n```\n\n**Don't use .id() when**:\n- You just need to update view content (use bindings instead)\n- Trying to fix update issues (investigate root cause instead)\n- Identity is already stable\n\n### Debugging Identity Issues\n\n#### 1. Self._printChanges()\n```swift\nvar body: some View {\n    let _ = Self._printChanges()\n    \u002F\u002F Check if \"@self changed\" appears when you don't expect\n}\n```\n\n#### 2. Check .id() modifiers\nSearch codebase for `.id()` - are IDs changing unexpectedly?\n\n#### 3. Check conditionals\nViews in `if\u002Felse` change position → different identity.\n\n**Fix**: Use `.opacity()` or stable `.id()` instead.\n\n### Identity Quick Reference\n\n| Symptom | Likely Cause | Fix |\n|---------|--------------|-----|\n| State resets | Identity change | Use `.opacity()` instead of `if` |\n| No animation | Identity change | Remove `.id()` or use stable ID |\n| ForEach jumps | Non-unique ID | Use unique, stable IDs |\n| Unexpected recreation | Conditional position | Add explicit `.id()` |\n\n**See also**: [WWDC21: Demystify SwiftUI](https:\u002F\u002Fdeveloper.apple.com\u002Fvideos\u002Fplay\u002Fwwdc2021\u002F10022\u002F)\n\n---\n\n## Pressure Scenarios and Real-World Constraints\n\nWhen you're under deadline pressure, you'll be tempted to shortcuts that hide problems instead of fixing them.\n\n### Scenario 1: \"Preview keeps crashing, we ship tomorrow\"\n\n#### Red flags you might hear\n- \"Just rebuild everything\"\n- \"Delete derived data and don't worry about it\"\n- \"Ship without validating in preview\"\n- \"It works on my machine, good enough\"\n\n**The danger**: You skip diagnosis, cache issue recurs after 2 weeks in production, you're debugging while users hit crashes.\n\n**What to do instead** (5-minute protocol, total):\n1. Restart Preview Canvas: `Cmd+Option+P` (30 seconds)\n2. Restart Xcode (2 minutes)\n3. Nuke derived data: `rm -rf ~\u002FLibrary\u002FDeveloper\u002FXcode\u002FDerivedData` (30 seconds)\n4. Rebuild: `Cmd+B` (2 minutes)\n5. Still broken? Use the dependency or initialization decision trees above\n\n**Time cost**: 5 minutes diagnosis + 2 minutes fix = **7 minutes total**\n\n**Cost of skipping**: 30 min shipping + 24 hours debug cycle = **24+ hours total**\n\n---\n\n### Scenario 2: \"View won't update, let me just wrap it in @ObservedObject\"\n\n#### Red flags you might think\n- \"Adding @ObservedObject everywhere will fix it\"\n- \"Use ObservableObject as a band-aid\"\n- \"Add @Published to random properties\"\n- \"It's probably a binding issue, I'll just create a custom binding\"\n\n**The danger**: You're treating symptoms, not diagnosing. Same view won't update in other contexts. You've just hidden the bug.\n\n**What to do instead** (2-minute diagnosis):\n1. Can you reproduce in a minimal preview? If NO → cache corruption (see Scenario 1)\n2. If YES: Test each root cause in order:\n   - Does the view have @State that you're modifying directly? → Struct Mutation\n   - Did the view move into a conditional recently? → View Recreation\n   - Are you passing bindings to children that have changed? → Lost Binding Identity\n   - Only if none of above: Missing Observer\n3. Fix the actual root cause, not with @ObservedObject band-aid\n\n**Decision principle**: If you can't name the specific root cause, you haven't diagnosed yet. Don't code until you can answer \"the problem is struct mutation because...\".\n\n---\n\n### Scenario 2b: \"Intermittent updates - it works sometimes, not always\"\n\n#### Red flags you might think\n- \"It must be a threading issue, let me add @MainActor everywhere\"\n- \"Let me try @ObservedObject, @State, and custom Binding until something works\"\n- \"Delete DerivedData and hope cache corruption fixes it\"\n- \"This is unfixable, let me ship without this feature\"\n\n**The danger**: You're exhausted after 2 hours of guessing. You're 17 hours from App Store submission. You're panicking. Every minute feels urgent, so you stop diagnosing and start flailing.\n\nIntermittent bugs are the MOST important to diagnose correctly. One wrong guess now creates a new bug. You ship with a broken view AND a new bug. App Store rejects you. You miss launch.\n\n**What to do instead** (60-minute systematic diagnosis):\n\n**Step 1: Reproduce in preview** (15 min)\n- Create minimal preview of just the broken view\n- Tap\u002Finteract 20 times\n- Does it fail intermittently, consistently, or never?\n  - **Fails in preview**: Real bug in your code, use decision tree above\n  - **Works in preview but fails in app**: Cache or environment issue, use Preview Crashes decision tree\n  - **Can't reproduce at all**: Intermittent race condition, investigate further\n\n**Step 2: Isolate the variable** (15 min)\n- If it's intermittent in preview: Likely view recreation\n  - Did the view recently move into a conditional? Remove it and test\n  - Did you add `if` logic that might recreate the parent? Remove it and test\n- If it works in preview but fails in app: Likely environment\u002Fcache issue\n  - Try on different device\u002Fsimulator\n  - Try after clearing DerivedData\n\n**Step 3: Apply the specific fix** (30 min)\n- Once you've identified view recreation: Use `.opacity()` instead of conditionals\n- Once you've identified struct mutation: Use full reassignment\n- Once you've verified it's cache: Nuke DerivedData properly\n\n**Step 4: Verify 100% reliability** (until submission)\n- Run the same interaction 30+ times\n- Test on multiple devices\u002Fsimulators\n- Get QA to verify\n- Only ship when it's 100% reproducible (not the bug, the FIX)\n\n**Time cost**: 60 minutes diagnosis + 30 minutes fix + confidence = **submit at 9am**\n\n**Cost of guessing**: 2 hours already + 3 more hours guessing + new bug introduced + crash reports post-launch + emergency patch + reputation damage = **miss launch + post-launch chaos**\n\n**The decision principle**: Intermittent bugs require SYSTEMATIC diagnosis. The slower you go in diagnosis, the faster you get to the fix. Guessing is the fastest way to disaster.\n\n#### Professional script for co-leads who suggest guessing\n\n> \"I appreciate the suggestion. Adding @ObservedObject everywhere is treating the symptom, not the root cause. The skill says intermittent bugs create NEW bugs when we guess. I need 60 minutes for systematic diagnosis. If I can't find the root cause by then, we'll disable the feature and ship a clean v1.1. The math shows we have time—I can complete diagnosis, fix, AND verification before the deadline.\"\n\n---\n\n### Scenario 3: \"Layout looks wrong on iPad, we're out of time\"\n\n#### Red flags you might think\n- \"Add some padding and magic numbers\"\n- \"It's probably a safe area thing, let me just ignore it\"\n- \"Let's lock this to iPhone only\"\n- \"GeometryReader will solve this\"\n\n**The danger**: Magic numbers break on other sizes. SafeArea ignoring is often wrong. Locking to iPhone means you ship a broken iPad experience.\n\n**What to do instead** (3-minute diagnosis):\n1. Run in simulator or device\n2. Use Debug View Hierarchy: Debug menu → View Hierarchy (takes 30 seconds to load)\n3. Check: Is the problem SafeArea, ZStack ordering, or GeometryReader sizing?\n4. Use the correct pattern from the Quick Reference above\n\n**Time cost**: 3 minutes diagnosis + 5 minutes fix = **8 minutes total**\n\n**Cost of magic numbers**: Ship wrong, report 2 weeks later, debug 4 hours, patch in update = **2+ weeks delay**\n\n---\n\n## Quick Reference\n\n### Common View Update Fixes\n\n```swift\n\u002F\u002F Fix 1: Reassign the full struct\n@State var items: [String] = []\nvar newItems = items\nnewItems.append(\"new\")\nself.items = newItems\n\n\u002F\u002F Fix 2: Pass binding correctly\n@State var value = \"\"\nChildView(text: $value)  \u002F\u002F Pass binding, not value\n\n\u002F\u002F Fix 3: Preserve view identity\nView().opacity(isVisible ? 1 : 0)  \u002F\u002F Not: if isVisible { View() }\n\n\u002F\u002F Fix 4: Observe the object\n@StateObject var model = MyModel()\n@ObservedObject var model: MyModel\n```\n\n### Common Preview Fixes\n\n```swift\n\u002F\u002F Fix 1: Provide dependencies\n#Preview {\n    ContentView()\n        .environmentObject(AppModel())\n}\n\n\u002F\u002F Fix 2: Safe defaults\n@State var index = 0  \u002F\u002F Not 10, if array has 3 items\n\n\u002F\u002F Fix 3: Nuke cache\n\u002F\u002F Terminal: rm -rf ~\u002FLibrary\u002FDeveloper\u002FXcode\u002FDerivedData\n```\n\n### Common Layout Fixes\n\n```swift\n\u002F\u002F Fix 1: Z-order\nRectangle().zIndex(1)\n\n\u002F\u002F Fix 2: Constrain GeometryReader\nGeometryReader { geo in ... }.frame(height: 100)\n\n\u002F\u002F Fix 3: SafeArea\nZStack { ... }.ignoresSafeArea()\n\n\u002F\u002F Fix 4: Modifier order\nText().cornerRadius(8).padding()  \u002F\u002F Corners first\n```\n\n## Real-World Examples\n\n### Example 1: List Item Doesn't Update When Tapped\n\n**Scenario**: You have a list of tasks. When you tap a task to mark it complete, the checkmark should appear, but it doesn't.\n\n**Code**:\n```swift\nstruct TaskListView: View {\n    @State var tasks: [Task] = [...]\n\n    var body: some View {\n        List {\n            ForEach(tasks, id: \\.id) { task in\n                HStack {\n                    Image(systemName: task.isComplete ? \"checkmark.circle.fill\" : \"circle\")\n                    Text(task.title)\n                    Spacer()\n                    Button(\"Done\") {\n                        \u002F\u002F ❌ WRONG: Direct mutation\n                        task.isComplete.toggle()\n                    }\n                }\n            }\n        }\n    }\n}\n```\n\n**Diagnosis using the skill**:\n1. Can you reproduce in preview? YES\n2. Are you modifying the struct directly? YES → **Struct Mutation** (Root Cause 1)\n\n**Fix**:\n```swift\nButton(\"Done\") {\n    \u002F\u002F ✅ RIGHT: Full reassignment\n    if let index = tasks.firstIndex(where: { $0.id == task.id }) {\n        tasks[index].isComplete.toggle()\n    }\n}\n```\n\n**Why this works**: SwiftUI detects the array reassignment, triggering a redraw. The task in the List updates.\n\n---\n\n### Example 2: Preview Crashes with \"No Such Module\"\n\n**Scenario**: You created a custom data model. It works fine in the app, but the preview crashes with \"Cannot find 'CustomModel' in scope\".\n\n**Code**:\n```swift\nimport SwiftUI\n\n\u002F\u002F ❌ WRONG: Preview missing the dependency\n#Preview {\n    TaskDetailView(task: Task(...))\n}\n\nstruct TaskDetailView: View {\n    @Environment(\\.modelContext) var modelContext\n    let task: Task  \u002F\u002F Custom model\n\n    var body: some View {\n        Text(task.title)\n    }\n}\n```\n\n**Diagnosis using the skill**:\n1. What's the error? \"Cannot find in scope\" → **Missing Dependency** (Error Type 1)\n2. What does TaskDetailView need? The Task model and modelContext\n\n**Fix**:\n```swift\n#Preview {\n    let config = ModelConfiguration(isStoredInMemoryOnly: true)\n    let container = try! ModelContainer(for: Task.self, configurations: config)\n\n    return TaskDetailView(task: Task(title: \"Sample\"))\n        .modelContainer(container)\n}\n```\n\n**Why this works**: Providing the environment object and model container satisfies the view's dependencies. Preview loads successfully.\n\n---\n\n### Example 3: Text Field Value Changes Don't Appear\n\n**Scenario**: You have a search field. You type characters, but the text doesn't appear in the UI. However, the search results DO update.\n\n**Code**:\n```swift\nstruct SearchView: View {\n    @State var searchText = \"\"\n\n    var body: some View {\n        VStack {\n            \u002F\u002F ❌ WRONG: Passing constant binding\n            TextField(\"Search\", text: .constant(searchText))\n\n            Text(\"Results for: \\(searchText)\")  \u002F\u002F This updates\n            List {\n                ForEach(results(for: searchText), id: \\.self) { result in\n                    Text(result)\n                }\n            }\n        }\n    }\n\n    func results(for text: String) -> [String] {\n        \u002F\u002F Returns filtered results\n    }\n}\n```\n\n**Diagnosis using the skill**:\n1. Can you reproduce in preview? YES\n2. Are you passing a binding to a child view? YES (TextField)\n3. Is it a constant binding? YES → **Lost Binding Identity** (Root Cause 2)\n\n**Fix**:\n```swift\n\u002F\u002F ✅ RIGHT: Pass the actual binding\nTextField(\"Search\", text: $searchText)\n```\n\n**Why this works**: `$searchText` passes a two-way binding. TextField writes changes back to @State, triggering a redraw. Text field now shows typed characters.\n\n---\n\n## Simulator Verification\n\nAfter fixing SwiftUI issues, verify with visual confirmation in the simulator.\n\n### Why Simulator Verification Matters\n\nSwiftUI previews don't always match simulator behavior:\n- **Different rendering** — Some visual effects only work on device\u002Fsimulator\n- **Different timing** — Animations may behave differently\n- **Different state** — Full app lifecycle vs isolated preview\n\n**Use simulator verification for**:\n- Layout fixes (spacing, alignment, sizing)\n- View update fixes (state changes, bindings)\n- Animation and gesture issues\n- Before\u002Fafter visual comparison\n\n### Quick Verification Workflow\n\n```bash\n# 1. Take \"before\" screenshot\n\u002Faxiom:screenshot\n\n# 2. Apply your fix\n\n# 3. Rebuild and relaunch\nxcodebuild build -scheme YourScheme\n\n# 4. Take \"after\" screenshot\n\u002Faxiom:screenshot\n\n# 5. Compare screenshots to verify fix\n```\n\n### Navigating to Problem Screens\n\nIf the bug is deep in your app, use debug deep links to navigate directly:\n\n```bash\n# 1. Add debug deep links (see deep-link-debugging skill)\n# Example: debug:\u002F\u002Fsettings, debug:\u002F\u002Frecipe-detail?id=123\n\n# 2. Navigate and capture\nxcrun simctl openurl booted \"debug:\u002F\u002Fproblem-screen\"\nsleep 1\n\u002Faxiom:screenshot\n```\n\n### Full Simulator Testing\n\nFor complex scenarios (state setup, multiple steps, log analysis):\n\n```bash\n\u002Faxiom:test-simulator\n```\n\nThen describe what you want to test:\n- \"Navigate to the recipe editor and verify the layout fix\"\n- \"Test the profile screen with empty state\"\n- \"Verify the animation doesn't stutter anymore\"\n\n### Before\u002FAfter Example\n\n**Before fix** (view not updating):\n```bash\n# 1. Reproduce bug\nxcrun simctl openurl booted \"debug:\u002F\u002Frecipe-list\"\nsleep 1\nxcrun simctl io booted screenshot \u002Ftmp\u002Fbefore-fix.png\n# Screenshot shows: Tapping star doesn't update UI\n```\n\n**After fix** (added @State binding):\n```bash\n# 2. Test fix\nxcrun simctl openurl booted \"debug:\u002F\u002Frecipe-list\"\nsleep 1\nxcrun simctl io booted screenshot \u002Ftmp\u002Fafter-fix.png\n# Screenshot shows: Star updates immediately when tapped\n```\n\n**Time saved**: 60%+ faster iteration with visual verification vs manual navigation\n\n---\n\n## Resources\n\n**WWDC**: 2025-256, 2025-306, 2023-10160, 2023-10149, 2021-10022\n\n**Docs**: \u002Fswiftui\u002Fmanaging-model-data-in-your-app, \u002Fswiftui, \u002Fswiftui\u002Fstate-and-data-flow, \u002Fxcode\u002Fpreviews, \u002Fobservation\n\n**Skills**: axiom-swiftui-performance, axiom-swiftui-debugging-diag, axiom-xcode-debugging, axiom-swift-concurrency, axiom-lldb (LLDB debugging workflows beyond Self._printChanges)\n\n\n",{"name":5,"license":15,"metadata":41,"description":7},{"version":42,"last-updated":43},"1.3.0","Added Self._printChanges() debugging, @Observable patterns (iOS 17+), @Bindable, view identity section, and cross-references to swiftui-performance","main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-swiftui-debugging",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill axiom-swiftui-debugging",{"tool":59,"command":60},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill axiom-swiftui-debugging",{"tool":62,"command":63},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill axiom-swiftui-debugging","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002FCharlesWiltgen\u002FAxiom\u002Faxiom-swiftui-debugging\u002FSKILL.md",true,[67],{"path":68,"resourceType":69,"resourceTypeDesc":70,"sizeBytes":71,"sourceHtmlUrl":72},"_AIWF_IMPORT.json","REFERENCE","参考文档",335,"https:\u002F\u002Fgithub.com\u002FiDorgham\u002FWorkspace-Factory\u002Fblob\u002Fmaster\u002Ffactory\u002Flibrary\u002Fskills\u002Fgithub_imports\u002Frowan\u002F_AIWF_IMPORT.json",[74,83,92,101,107,113],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":36},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[80,81,82],"model","model hierarchy","model hierarchy skill",{"skillNo":84,"name":85,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":36},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[89,90,91],"MCP","zoom","zoom mcp",{"skillNo":93,"name":94,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":36},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[98,99,100,90],"sdk","zoom apps sdk","apps",{"skillNo":102,"name":103,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":36},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[103],{"skillNo":108,"name":109,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":36},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[109],{"skillNo":114,"name":115,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":116,"categories":117,"keywords":118,"publishedAt":36},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[115]]