swiftui-view-refactor
SwiftUI View Refactor
Overview
Apply a consistent structure and dependency pattern to SwiftUI views, with a focus on ordering, Model-View (MV) patterns, careful view model handling, and correct Observation usage.
Core Guidelines
1) View ordering (top → bottom)
- Environment
private/publiclet@State/ other stored properties- computed
var(non-view) initbody- computed view builders / other view helpers
- helper / async functions
2) Prefer MV (Model-View) patterns
- Default to MV: Views are lightweight state expressions; models/services own business logic.
- Favor
@State,@Environment,@Query, andtask/onChangefor orchestration. - Inject services and shared models via
@Environment; keep views small and composable. - Split large views into subviews rather than introducing a view model.
3) Split large bodies and view properties
- If
bodygrows beyond a screen or has multiple logical sections, split it into smaller subviews. - Extract large computed view properties (
var header: some View { ... }) into dedicatedViewtypes when they carry state or complex branching. - It's fine to keep related subviews as computed view properties in the same file; extract to a standalone
Viewstruct only when it structurally makes sense or when reuse is intended. - Prefer passing small inputs (data, bindings, callbacks) over reusing the entire parent view state.
Example (extracting a section):
var body: some View {
VStack(alignment: .leading, spacing: 16) {
HeaderSection(title: title, isPinned: isPinned)
DetailsSection(details: details)
ActionsSection(onSave: onSave, onCancel: onCancel)
}
}
Example (long body → shorter body + computed views in the same file):
var body: some View {
List {
header
filters
results
footer
}
}
private var header: some View {
VStack(alignment: .leading, spacing: 6) {
Text(title).font(.title2)
Text(subtitle).font(.subheadline)
}
}
private var filters: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(filterOptions, id: \.self) { option in
FilterChip(option: option, isSelected: option == selectedFilter)
.onTapGesture { selectedFilter = option }
}
}
}
}
Example (extracting a complex computed view):
private var header: some View {
HeaderSection(title: title, subtitle: subtitle, status: status)
}
private struct HeaderSection: View {
let title: String
let subtitle: String?
let status: Status
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text(title).font(.headline)
if let subtitle { Text(subtitle).font(.subheadline) }
StatusBadge(status: status)
}
}
}
4) View model handling (only if already present)
- Do not introduce a view model unless the request or existing code clearly calls for one.
- If a view model exists, make it non-optional when possible.
- Pass dependencies to the view via
init, then pass them into the view model in the view'sinit. - Avoid
bootstrapIfNeededpatterns.
Example (Observation-based):
@State private var viewModel: SomeViewModel
init(dependency: Dependency) {
_viewModel = State(initialValue: SomeViewModel(dependency: dependency))
}
5) Observation usage
- For
@Observablereference types, store them as@Statein the root view. - Pass observables down explicitly as needed; avoid optional state unless required.
Workflow
- Reorder the view to match the ordering rules.
- Favor MV: move lightweight orchestration into the view using
@State,@Environment,@Query,task, andonChange. - If a view model exists, replace optional view models with a non-optional
@Stateview model initialized ininitby passing dependencies from the view. - Confirm Observation usage:
@Statefor root@Observableview models, no redundant wrappers. - Keep behavior intact: do not change layout or business logic unless requested.
Notes
- Prefer small, explicit helpers over large conditional blocks.
- Keep computed view builders below
bodyand non-view computed vars aboveinit. - For MV-first guidance and rationale, see
references/mv-patterns.md.
More from vladimirbrejcha/ios-ai-skills
swiftui-simulator-ui
Run SwiftUI apps in iOS Simulator and capture screenshots for visual verification. Use when building UI, reviewing layouts, validating designs, or when you need to see what SwiftUI code looks like. Essential for any UI work requiring visual feedback.
9apple-docs-research
Use when researching or implementing anything related to Apple platforms (iOS, iPadOS, macOS, watchOS, tvOS, visionOS), Swift/Objective-C APIs, Apple frameworks, WWDC sessions, or Apple Developer Documentation. Triggers include: \"find Apple's docs\", \"latest API guidance\", \"WWDC session\", \"platform availability\", \"SwiftUI/UIKit/AppKit/Combine/AVFoundation/etc.\", or any Apple SDK coding question where authoritative docs are needed. Always use the apple-docs MCP tools for discovery and citations instead of general web search.
8app-store-optimisation-codex
App Store Optimization (ASO) workflows for Apple App Store and Google Play Store. Use when Codex is asked to research keywords, optimize app metadata (titles, subtitles, descriptions, keywords), analyze competitors, plan A/B tests, compute ASO scores, analyze reviews, plan localization, or build launch/update checklists for mobile apps.
6apple-doc-research
Use when researching or implementing anything related to Apple platforms (iOS, iPadOS, macOS, watchOS, tvOS, visionOS), Swift/Objective-C APIs, Apple frameworks, WWDC sessions, or Apple Developer Documentation. Triggers include: \"find Apple's docs\", \"latest API guidance\", \"WWDC session\", \"platform availability\", \"SwiftUI/UIKit/AppKit/Combine/AVFoundation/etc.\", or any Apple SDK coding question where authoritative docs are needed. Always use the apple-docs MCP tools for discovery and citations instead of general web search.
5ios-xcodegen
XcodeGen workflows for iOS/iPadOS apps: generate projects from project.yml/project.yaml, fix build/test destination issues, wire asset catalogs, configure test hosts, manage SwiftPM resolution in CI, and resolve App Store packaging errors related to embedded static libraries.
5code-review
Review pull requests, commits, or diffs for high-signal engineering issues and merge risk. Use when asked to review code, audit a patch, find bugs, or provide merge readiness feedback. Focus on defects introduced by the proposed changes (correctness, security, performance, reliability, and maintainability) and report actionable findings with severity, confidence, and precise code locations.
4