SWE-Bench Mobile: Defensive Agent Strategy for Production Mobile Development
This skill equips Claude to tackle production-grade mobile (especially iOS) development tasks using
the Defensive Programming agent strategy identified in SWE-Bench Mobile research. The core insight:
simple prompts focused on edge-case robustness outperform complex multi-step checklists by 7.4%,
and agent architecture choices (tool integration, context management, iterative refinement) matter
as much as raw model capability -- the same model shows up to 6x performance variance across
different agent scaffolding. This skill encodes the winning patterns.
When to Use
- When the user provides a PRD (Product Requirement Document) and/or Figma design and asks you to implement a mobile feature
- When working in a large mixed Swift/Objective-C iOS codebase (or any multi-language mobile project)
- When generating a unified diff patch for a production mobile app
- When the user asks to implement a UI component, data management feature, gesture handler, or networking layer in an iOS app
- When a mobile task requires modifying 3+ files across model, view, and controller layers
- When the user needs help structuring agent-assisted mobile development workflows
- When debugging why an AI-generated mobile patch fails tests or misses requirements
Key Technique: Defensive Programming over Comprehensive Checklists
The SWE-Bench Mobile benchmark evaluated 22 agent-model configurations on 50 industry-level iOS
tasks (449 test cases). The highest-performing prompt strategy was Defensive Programming: a
focused instruction to write robust, production-ready code that handles edge cases gracefully --
nil values, empty data, network timeouts, concurrent operations. This simple strategy achieved
26.7% test pass rate vs. 19.3% baseline, while a verbose "Comprehensive" checklist approach
dropped to just 4% task success (vs. 10% for Defensive Programming).
Why does simplicity win? Overly detailed process instructions misdirect attention toward workflow
compliance rather than implementation correctness. The Defensive Programming prompt keeps the agent
focused on what matters: generating code that actually works under real conditions. The research
also found that agent architecture is a first-class concern -- Cursor achieved 12% task success
with Opus 4.5 while OpenCode achieved only 2% with the same model. The difference comes from
tool integration quality, context window management, and iterative self-correction loops.
The dominant failure modes reveal where to focus effort: missing feature flags (54% of failures),
missing data models (22%), incomplete file coverage (11-15%), and missing UI components (11-15%).
Tasks requiring 1-2 files achieved 18% success vs. only 2% for 7+ files, showing that cross-file
reasoning in unfamiliar language ecosystems is the key bottleneck.
Step-by-Step Workflow
Parse the requirement into atomic deliverables. Extract every concrete output from the PRD
or user description: data models, UI components, API integrations, navigation flows, feature
flags. Create an explicit checklist -- the #1 failure mode is omitting required artifacts.
Inventory the codebase architecture before writing code. Map the project structure: find
existing patterns for models, views, controllers/coordinators, networking layers, and feature
flags. In Swift/ObjC codebases, identify bridging headers and mixed-language boundaries. Search
for naming conventions, base classes, and dependency injection patterns.
Identify ALL files that need modification. For each deliverable from step 1, trace which
files must change. Err on the side of including more files -- incomplete file coverage causes
11-15% of failures. Check for: model definitions, view implementations, view models/presenters,
coordinators/routers, dependency registration, feature flag declarations, and test targets.
Apply the Defensive Programming mindset to every code block. For each function or component:
- Handle nil/optional values explicitly (guard let, if let, nil coalescing)
- Account for empty collections and missing data
- Add timeout handling for async operations
- Consider thread safety for concurrent access
- Respect iOS lifecycle (viewDidLoad vs. viewWillAppear, dealloc patterns)
Implement data models and feature flags FIRST. These are prerequisite layers. Define structs/
classes, Codable conformances, Core Data entities, or Realm objects before building UI or
networking. Register feature flags in the project's existing flag system -- missing flags account
for 54% of failures.
Build UI components referencing Figma specs precisely. Match spacing, colors, typography, and
layout constraints to the design. Use Auto Layout or SwiftUI modifiers that correspond to the
design system. Verify that dynamic content (variable-length text, missing images) degrades
gracefully.
Wire up networking and data flow with error boundaries. Connect API calls, local persistence,
and state management. Wrap each integration point in error handling that surfaces meaningful
feedback rather than silent failures.
Generate a minimal, correct unified diff patch. Include only the files that must change.
Verify the patch applies cleanly against the target branch. Each hunk should have sufficient
context lines (3+) for unambiguous application.
Self-review against the original requirements checklist. Walk through every deliverable from
step 1 and confirm it appears in the implementation. Check for the top failure modes: missing
feature flags, missing data models, incomplete file coverage, missing UI components.
Validate with available test infrastructure. If tests exist, run them. If generating test-
compatible output, ensure structural correctness (correct class names, method signatures,
protocol conformances) since evaluation often uses diff-based structural analysis.
Concrete Examples
Example 1: Implementing a Profile Settings Screen from PRD
User: "Here's the PRD for a new Profile Settings screen. It should show user avatar, name, email,
and a list of toggleable preferences. The Figma is attached. Implement this in our Swift codebase."
Approach:
- Parse PRD deliverables: ProfileSettingsViewController, ProfileSettingsViewModel,
UserPreference model, PreferenceCell, feature flag
profile_settings_v2_enabled
- Search codebase for existing patterns:
# Find existing ViewControllers for pattern reference
find . -name "*ViewController.swift" | head -20
# Find feature flag registration
grep -r "FeatureFlag" --include="*.swift" -l
# Find existing table view cell patterns
grep -r "UITableViewCell" --include="*.swift" -l | head -10
- Identify files to create/modify: new model file, new VC, new VM, new cell,
feature flag registration file, coordinator to add navigation route
- Implement with defensive patterns:
struct UserPreference: Codable {
let id: String
let title: String
let isEnabled: Bool
// Defensive: handle missing keys gracefully
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.title = try container.decodeIfPresent(String.self, forKey: .title) ?? "Unknown"
self.isEnabled = try container.decodeIfPresent(Bool.self, forKey: .isEnabled) ?? false
}
}
- Register feature flag, wire navigation, verify all 6 deliverables are covered
Output: Unified diff patch touching 6 files with defensive nil handling throughout.
Example 2: Fixing a Gesture Interaction Bug Across Multiple Files
User: "Our swipe-to-delete gesture on the Favorites list crashes when the list is empty and the
user swipes. Fix this in our mixed Swift/ObjC codebase."
Approach:
- Locate the crash site -- search for swipe/delete gesture handling in Favorites:
grep -r "swipe\|deleteRow\|commitEditingStyle" --include="*.swift" --include="*.m" -l
- Identify the defensive gap: likely an unguarded array index access when data source is empty
- Apply defensive fix with guard:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle,
forRowAt indexPath: IndexPath) {
guard editingStyle == .delete else { return }
guard indexPath.row < favorites.count else { return } // Defensive: bounds check
let item = favorites[indexPath.row]
favorites.remove(at: indexPath.row)
tableView.performBatchUpdates({
tableView.deleteRows(at: [indexPath], with: .automatic)
}, completion: { _ in
// Defensive: verify consistency after animation
if self.favorites.isEmpty {
self.showEmptyState()
}
})
}
- Check if the ObjC bridging header or any ObjC callers need updates
- Verify empty-state UI is shown after last item deletion
Output: Patch modifying 2 files -- the gesture handler and the empty state view.
Example 3: Structuring an Agent Workflow for a Complex Mobile Feature
User: "I need to add offline caching for our feed. This touches networking, persistence, UI, and
sync logic. How should I structure the agent workflow?"
Approach:
- Break into atomic tasks ordered by dependency:
- Task 1: Define CachedFeedItem data model + Core Data schema
- Task 2: Implement FeedCacheManager (write/read/evict)
- Task 3: Add feature flag
offline_feed_cache_enabled
- Task 4: Modify FeedNetworkService to write-through to cache
- Task 5: Update FeedViewController to load from cache on network failure
- Task 6: Add sync conflict resolution logic
- Recommend tackling each task as a separate focused prompt rather than one mega-prompt
(simpler prompts outperform comprehensive ones by 7.4%)
- For each task, apply defensive programming: handle empty cache, stale data, migration from
no-cache to cached state, disk full errors, and concurrent read/write access
- Verify each task independently before combining
Output: A structured task plan with 6 focused sub-tasks, each producing a testable patch.
Best Practices
- Do: Keep implementation prompts focused on one concern at a time. The research shows simple,
targeted prompts outperform complex checklists by a wide margin.
- Do: Always create an explicit deliverables checklist from the PRD before coding. Walk it
after implementation. Missing artifacts are the #1 failure category.
- Do: Inventory the codebase first. Spend time reading existing patterns before generating
code. Match naming conventions, architecture patterns, and dependency injection styles.
- Do: Treat feature flags as first-class deliverables. 54% of failures stem from missing
production deployment toggles.
- Avoid: Writing a long, multi-part system prompt with step-by-step checklists for the agent.
This misdirects attention toward process compliance rather than code correctness.
- Avoid: Attempting 7+ file changes in a single pass. Success drops from 18% (1-2 files) to
2% (7+ files). Break large features into smaller, independently testable patches.
Error Handling
| Failure Mode |
Frequency |
Mitigation |
| Missing feature flags |
54% |
Always search for and match the project's feature flag system before submitting |
| Missing data models |
22% |
Implement models first; treat them as blocking prerequisites |
| Incomplete file coverage |
11-15% |
Trace every requirement to specific files; check coordinators, DI containers, and navigation |
| Missing UI components |
11-15% |
Cross-reference Figma/PRD for every visual element; verify empty/loading/error states |
| Cross-language bridging errors |
Common in ObjC/Swift |
Check bridging headers, @objc annotations, NS_SWIFT_NAME macros |
| Async race conditions |
Common in gesture/networking |
Use DispatchQueue barriers, actors (Swift 5.5+), or serial queues for shared state |
Limitations
- This approach is optimized for iOS (Swift/Objective-C) codebases. Android (Kotlin/Java) and
cross-platform (React Native, Flutter) have different architectural patterns -- adapt the
checklist accordingly.
- Even the best agent configuration achieves only 12% task success on the full benchmark.
Production mobile development still requires substantial human review and iteration.
- Gesture and interaction tasks (8% avg pass rate) and media/asset tasks (9.8%) remain
particularly difficult -- expect to need more manual intervention for these categories.
- The defensive programming approach helps most with data management (15.3% pass rate) and
UI component tasks (12.5%). It has less impact on tasks requiring deep framework knowledge
(e.g., custom Core Animation, Metal shaders).
- Multi-modal inputs (Figma designs) cannot be perfectly translated to code by current agents.
Pixel-perfect implementation still requires human visual QA.
Reference
Paper: SWE-Bench Mobile: Can Large Language Model Agents Develop Industry-Level Mobile Applications? (Tian et al., 2026)
Leaderboard & Toolkit: swebenchmobile.com
Key takeaway: Agent scaffolding design matters as much as model capability. Use simple, defensive
prompts focused on edge-case robustness rather than comprehensive process checklists, and break
large mobile features into small (1-3 file) independently testable patches.
1---2name: swe-bench-mobile-agents-develop3description: Apply defensive programming and agent-architecture patterns from SWE-Bench Mobile to tackle production iOS/mobile development tasks. Optimizes how Claude navigates large mixed-language codebases, interprets multi-modal inputs (PRDs + Figma designs), and generates robust patches. Use when: "build this iOS feature from a PRD", "implement this Figma design in Swift", "fix this mobile app issue across multiple files", "generate a patch for this iOS codebase", "help me with production mobile development", "defensive programming for mobile code".4---56# SWE-Bench Mobile: Defensive Agent Strategy for Production Mobile Development78This skill equips Claude to tackle production-grade mobile (especially iOS) development tasks using9the Defensive Programming agent strategy identified in SWE-Bench Mobile research. The core insight:10simple prompts focused on edge-case robustness outperform complex multi-step checklists by 7.4%,11and agent architecture choices (tool integration, context management, iterative refinement) matter12as much as raw model capability -- the same model shows up to 6x performance variance across13different agent scaffolding. This skill encodes the winning patterns.1415## When to Use1617- When the user provides a PRD (Product Requirement Document) and/or Figma design and asks you to implement a mobile feature18- When working in a large mixed Swift/Objective-C iOS codebase (or any multi-language mobile project)19- When generating a unified diff patch for a production mobile app20- When the user asks to implement a UI component, data management feature, gesture handler, or networking layer in an iOS app21- When a mobile task requires modifying 3+ files across model, view, and controller layers22- When the user needs help structuring agent-assisted mobile development workflows23- When debugging why an AI-generated mobile patch fails tests or misses requirements2425## Key Technique: Defensive Programming over Comprehensive Checklists2627The SWE-Bench Mobile benchmark evaluated 22 agent-model configurations on 50 industry-level iOS28tasks (449 test cases). The highest-performing prompt strategy was **Defensive Programming**: a29focused instruction to write robust, production-ready code that handles edge cases gracefully --30nil values, empty data, network timeouts, concurrent operations. This simple strategy achieved3126.7% test pass rate vs. 19.3% baseline, while a verbose "Comprehensive" checklist approach32dropped to just 4% task success (vs. 10% for Defensive Programming).3334Why does simplicity win? Overly detailed process instructions misdirect attention toward workflow35compliance rather than implementation correctness. The Defensive Programming prompt keeps the agent36focused on what matters: generating code that actually works under real conditions. The research37also found that **agent architecture is a first-class concern** -- Cursor achieved 12% task success38with Opus 4.5 while OpenCode achieved only 2% with the same model. The difference comes from39tool integration quality, context window management, and iterative self-correction loops.4041The dominant failure modes reveal where to focus effort: missing feature flags (54% of failures),42missing data models (22%), incomplete file coverage (11-15%), and missing UI components (11-15%).43Tasks requiring 1-2 files achieved 18% success vs. only 2% for 7+ files, showing that cross-file44reasoning in unfamiliar language ecosystems is the key bottleneck.4546## Step-by-Step Workflow47481. **Parse the requirement into atomic deliverables.** Extract every concrete output from the PRD49 or user description: data models, UI components, API integrations, navigation flows, feature50 flags. Create an explicit checklist -- the #1 failure mode is omitting required artifacts.51522. **Inventory the codebase architecture before writing code.** Map the project structure: find53 existing patterns for models, views, controllers/coordinators, networking layers, and feature54 flags. In Swift/ObjC codebases, identify bridging headers and mixed-language boundaries. Search55 for naming conventions, base classes, and dependency injection patterns.56573. **Identify ALL files that need modification.** For each deliverable from step 1, trace which58 files must change. Err on the side of including more files -- incomplete file coverage causes59 11-15% of failures. Check for: model definitions, view implementations, view models/presenters,60 coordinators/routers, dependency registration, feature flag declarations, and test targets.61624. **Apply the Defensive Programming mindset to every code block.** For each function or component:63 - Handle nil/optional values explicitly (guard let, if let, nil coalescing)64 - Account for empty collections and missing data65 - Add timeout handling for async operations66 - Consider thread safety for concurrent access67 - Respect iOS lifecycle (viewDidLoad vs. viewWillAppear, dealloc patterns)68695. **Implement data models and feature flags FIRST.** These are prerequisite layers. Define structs/70 classes, Codable conformances, Core Data entities, or Realm objects before building UI or71 networking. Register feature flags in the project's existing flag system -- missing flags account72 for 54% of failures.73746. **Build UI components referencing Figma specs precisely.** Match spacing, colors, typography, and75 layout constraints to the design. Use Auto Layout or SwiftUI modifiers that correspond to the76 design system. Verify that dynamic content (variable-length text, missing images) degrades77 gracefully.78797. **Wire up networking and data flow with error boundaries.** Connect API calls, local persistence,80 and state management. Wrap each integration point in error handling that surfaces meaningful81 feedback rather than silent failures.82838. **Generate a minimal, correct unified diff patch.** Include only the files that must change.84 Verify the patch applies cleanly against the target branch. Each hunk should have sufficient85 context lines (3+) for unambiguous application.86879. **Self-review against the original requirements checklist.** Walk through every deliverable from88 step 1 and confirm it appears in the implementation. Check for the top failure modes: missing89 feature flags, missing data models, incomplete file coverage, missing UI components.909110. **Validate with available test infrastructure.** If tests exist, run them. If generating test-92 compatible output, ensure structural correctness (correct class names, method signatures,93 protocol conformances) since evaluation often uses diff-based structural analysis.9495## Concrete Examples9697**Example 1: Implementing a Profile Settings Screen from PRD**9899User: "Here's the PRD for a new Profile Settings screen. It should show user avatar, name, email,100and a list of toggleable preferences. The Figma is attached. Implement this in our Swift codebase."101102Approach:1031. Parse PRD deliverables: ProfileSettingsViewController, ProfileSettingsViewModel,104 UserPreference model, PreferenceCell, feature flag `profile_settings_v2_enabled`1052. Search codebase for existing patterns:106 ```bash107 # Find existing ViewControllers for pattern reference108 find . -name "*ViewController.swift" | head -20109 # Find feature flag registration110 grep -r "FeatureFlag" --include="*.swift" -l111 # Find existing table view cell patterns112 grep -r "UITableViewCell" --include="*.swift" -l | head -10113 ```1143. Identify files to create/modify: new model file, new VC, new VM, new cell,115 feature flag registration file, coordinator to add navigation route1164. Implement with defensive patterns:117 ```swift118 struct UserPreference: Codable {119 let id: String120 let title: String121 let isEnabled: Bool122123 // Defensive: handle missing keys gracefully124 init(from decoder: Decoder) throws {125 let container = try decoder.container(keyedBy: CodingKeys.self)126 self.id = try container.decode(String.self, forKey: .id)127 self.title = try container.decodeIfPresent(String.self, forKey: .title) ?? "Unknown"128 self.isEnabled = try container.decodeIfPresent(Bool.self, forKey: .isEnabled) ?? false129 }130 }131 ```1325. Register feature flag, wire navigation, verify all 6 deliverables are covered133134Output: Unified diff patch touching 6 files with defensive nil handling throughout.135136**Example 2: Fixing a Gesture Interaction Bug Across Multiple Files**137138User: "Our swipe-to-delete gesture on the Favorites list crashes when the list is empty and the139user swipes. Fix this in our mixed Swift/ObjC codebase."140141Approach:1421. Locate the crash site -- search for swipe/delete gesture handling in Favorites:143 ```bash144 grep -r "swipe\|deleteRow\|commitEditingStyle" --include="*.swift" --include="*.m" -l145 ```1462. Identify the defensive gap: likely an unguarded array index access when data source is empty1473. Apply defensive fix with guard:148 ```swift149 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle,150 forRowAt indexPath: IndexPath) {151 guard editingStyle == .delete else { return }152 guard indexPath.row < favorites.count else { return } // Defensive: bounds check153154 let item = favorites[indexPath.row]155 favorites.remove(at: indexPath.row)156157 tableView.performBatchUpdates({158 tableView.deleteRows(at: [indexPath], with: .automatic)159 }, completion: { _ in160 // Defensive: verify consistency after animation161 if self.favorites.isEmpty {162 self.showEmptyState()163 }164 })165 }166 ```1674. Check if the ObjC bridging header or any ObjC callers need updates1685. Verify empty-state UI is shown after last item deletion169170Output: Patch modifying 2 files -- the gesture handler and the empty state view.171172**Example 3: Structuring an Agent Workflow for a Complex Mobile Feature**173174User: "I need to add offline caching for our feed. This touches networking, persistence, UI, and175sync logic. How should I structure the agent workflow?"176177Approach:1781. Break into atomic tasks ordered by dependency:179 - Task 1: Define CachedFeedItem data model + Core Data schema180 - Task 2: Implement FeedCacheManager (write/read/evict)181 - Task 3: Add feature flag `offline_feed_cache_enabled`182 - Task 4: Modify FeedNetworkService to write-through to cache183 - Task 5: Update FeedViewController to load from cache on network failure184 - Task 6: Add sync conflict resolution logic1852. Recommend tackling each task as a separate focused prompt rather than one mega-prompt186 (simpler prompts outperform comprehensive ones by 7.4%)1873. For each task, apply defensive programming: handle empty cache, stale data, migration from188 no-cache to cached state, disk full errors, and concurrent read/write access1894. Verify each task independently before combining190191Output: A structured task plan with 6 focused sub-tasks, each producing a testable patch.192193## Best Practices194195- **Do:** Keep implementation prompts focused on one concern at a time. The research shows simple,196 targeted prompts outperform complex checklists by a wide margin.197- **Do:** Always create an explicit deliverables checklist from the PRD before coding. Walk it198 after implementation. Missing artifacts are the #1 failure category.199- **Do:** Inventory the codebase first. Spend time reading existing patterns before generating200 code. Match naming conventions, architecture patterns, and dependency injection styles.201- **Do:** Treat feature flags as first-class deliverables. 54% of failures stem from missing202 production deployment toggles.203- **Avoid:** Writing a long, multi-part system prompt with step-by-step checklists for the agent.204 This misdirects attention toward process compliance rather than code correctness.205- **Avoid:** Attempting 7+ file changes in a single pass. Success drops from 18% (1-2 files) to206 2% (7+ files). Break large features into smaller, independently testable patches.207208## Error Handling209210| Failure Mode | Frequency | Mitigation |211|---|---|---|212| Missing feature flags | 54% | Always search for and match the project's feature flag system before submitting |213| Missing data models | 22% | Implement models first; treat them as blocking prerequisites |214| Incomplete file coverage | 11-15% | Trace every requirement to specific files; check coordinators, DI containers, and navigation |215| Missing UI components | 11-15% | Cross-reference Figma/PRD for every visual element; verify empty/loading/error states |216| Cross-language bridging errors | Common in ObjC/Swift | Check bridging headers, @objc annotations, NS_SWIFT_NAME macros |217| Async race conditions | Common in gesture/networking | Use DispatchQueue barriers, actors (Swift 5.5+), or serial queues for shared state |218219## Limitations220221- This approach is optimized for iOS (Swift/Objective-C) codebases. Android (Kotlin/Java) and222 cross-platform (React Native, Flutter) have different architectural patterns -- adapt the223 checklist accordingly.224- Even the best agent configuration achieves only 12% task success on the full benchmark.225 Production mobile development still requires substantial human review and iteration.226- Gesture and interaction tasks (8% avg pass rate) and media/asset tasks (9.8%) remain227 particularly difficult -- expect to need more manual intervention for these categories.228- The defensive programming approach helps most with data management (15.3% pass rate) and229 UI component tasks (12.5%). It has less impact on tasks requiring deep framework knowledge230 (e.g., custom Core Animation, Metal shaders).231- Multi-modal inputs (Figma designs) cannot be perfectly translated to code by current agents.232 Pixel-perfect implementation still requires human visual QA.233234## Reference235236**Paper:** [SWE-Bench Mobile: Can Large Language Model Agents Develop Industry-Level Mobile Applications?](https://arxiv.org/abs/2602.09540v1) (Tian et al., 2026)237**Leaderboard & Toolkit:** [swebenchmobile.com](https://swebenchmobile.com)238239Key takeaway: Agent scaffolding design matters as much as model capability. Use simple, defensive240prompts focused on edge-case robustness rather than comprehensive process checklists, and break241large mobile features into small (1-3 file) independently testable patches.