Project Context
- SwiftUI views: !
grep -rl "var body.*some View" --include="*.swift" . 2>/dev/null | head -20 || echo "none found"
SwiftUI View Refactor
Lifecycle Position
Phase 5 (Review). After build is green. Previous: swiftui-ui-patterns review checklist, code-analyzer for architectural overview.
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/public let
@State / other stored properties
- computed
var (non-view)
init
body
- 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, and task/onChange for 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
body grows beyond a screen or has multiple logical sections, split it into smaller subviews.
- Extract large computed view properties (
var header: some View { ... }) into dedicated View types 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
View struct 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)
}
}
}
3b) Keep a stable view tree (avoid top-level conditional view swapping)
- Avoid patterns where a computed view (or
body) returns completely different root branches using if/else.
- Prefer a single stable base view, and place conditions inside sections/modifiers (
overlay, opacity, disabled, toolbar, row content, etc.).
- Root-level branch swapping can cause identity churn, broader invalidation, and extra recomputation in SwiftUI.
Prefer:
var body: some View {
List {
documentsListContent
}
.toolbar {
if canEdit {
editToolbar
}
}
}
Avoid:
var documentsListView: some View {
if canEdit {
editableDocumentsList
} else {
readOnlyDocumentsList
}
}
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's init.
- Avoid
bootstrapIfNeeded patterns.
Example (Observation-based):
@State private var viewModel: SomeViewModel
init(dependency: Dependency) {
_viewModel = State(initialValue: SomeViewModel(dependency: dependency))
}
5) Observation usage
- For
@Observable reference types, store them as @State in 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, and onChange.
- Ensure stable view structure: avoid top-level
if-based branch swapping; move conditions to localized sections/modifiers.
- If a view model exists, replace optional view models with a non-optional
@State view model initialized in init by passing dependencies from the view.
- Confirm Observation usage:
@State for root @Observable view 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
body and non-view computed vars above init.
- For MV-first guidance and rationale, see
references/mv-patterns.md.
Large-view handling
- When a SwiftUI view file exceeds ~300 lines, split it using extensions to group related helpers. Move async functions and helper functions into dedicated
private extensions, separated with // MARK: - comments that describe their purpose (e.g., // MARK: - Actions, // MARK: - Subviews, // MARK: - Helpers). Keep the main struct focused on stored properties, init, and body, with view-building computed vars also grouped via marks when the file is long.
1---2name: swiftui-view-refactor3description: Refactor and review SwiftUI view files for consistent structure, dependency injection, and Observation usage. Use when asked to clean up a SwiftUI view’s layout/ordering, handle view models safely (non-optional when possible), or standardize how dependencies and @Observable state are initialized and passed.4---56## Project Context78- SwiftUI views: !`grep -rl "var body.*some View" --include="*.swift" . 2>/dev/null | head -20 || echo "none found"`910# SwiftUI View Refactor1112## Lifecycle Position1314Phase 5 (Review). After build is green. Previous: `swiftui-ui-patterns` review checklist, `code-analyzer` for architectural overview.1516## Overview17Apply 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.1819## Core Guidelines2021### 1) View ordering (top → bottom)22- Environment23- `private`/`public` `let`24- `@State` / other stored properties25- computed `var` (non-view)26- `init`27- `body`28- computed view builders / other view helpers29- helper / async functions3031### 2) Prefer MV (Model-View) patterns32- Default to MV: Views are lightweight state expressions; models/services own business logic.33- Favor `@State`, `@Environment`, `@Query`, and `task`/`onChange` for orchestration.34- Inject services and shared models via `@Environment`; keep views small and composable.35- Split large views into subviews rather than introducing a view model.3637### 3) Split large bodies and view properties38- If `body` grows beyond a screen or has multiple logical sections, split it into smaller subviews.39- Extract large computed view properties (`var header: some View { ... }`) into dedicated `View` types when they carry state or complex branching.40- It's fine to keep related subviews as computed view properties in the same file; extract to a standalone `View` struct only when it structurally makes sense or when reuse is intended.41- Prefer passing small inputs (data, bindings, callbacks) over reusing the entire parent view state.4243Example (extracting a section):4445```swift46var body: some View {47 VStack(alignment: .leading, spacing: 16) {48 HeaderSection(title: title, isPinned: isPinned)49 DetailsSection(details: details)50 ActionsSection(onSave: onSave, onCancel: onCancel)51 }52}53```5455Example (long body → shorter body + computed views in the same file):5657```swift58var body: some View {59 List {60 header61 filters62 results63 footer64 }65}6667private var header: some View {68 VStack(alignment: .leading, spacing: 6) {69 Text(title).font(.title2)70 Text(subtitle).font(.subheadline)71 }72}7374private var filters: some View {75 ScrollView(.horizontal, showsIndicators: false) {76 HStack {77 ForEach(filterOptions, id: \.self) { option in78 FilterChip(option: option, isSelected: option == selectedFilter)79 .onTapGesture { selectedFilter = option }80 }81 }82 }83}84```8586Example (extracting a complex computed view):8788```swift89private var header: some View {90 HeaderSection(title: title, subtitle: subtitle, status: status)91}9293private struct HeaderSection: View {94 let title: String95 let subtitle: String?96 let status: Status9798 var body: some View {99 VStack(alignment: .leading, spacing: 4) {100 Text(title).font(.headline)101 if let subtitle { Text(subtitle).font(.subheadline) }102 StatusBadge(status: status)103 }104 }105}106```107108### 3b) Keep a stable view tree (avoid top-level conditional view swapping)109- Avoid patterns where a computed view (or `body`) returns completely different root branches using `if/else`.110- Prefer a single stable base view, and place conditions inside sections/modifiers (`overlay`, `opacity`, `disabled`, `toolbar`, row content, etc.).111- Root-level branch swapping can cause identity churn, broader invalidation, and extra recomputation in SwiftUI.112113Prefer:114115```swift116var body: some View {117 List {118 documentsListContent119 }120 .toolbar {121 if canEdit {122 editToolbar123 }124 }125}126```127128Avoid:129130```swift131var documentsListView: some View {132 if canEdit {133 editableDocumentsList134 } else {135 readOnlyDocumentsList136 }137}138```139140### 4) View model handling (only if already present)141- Do not introduce a view model unless the request or existing code clearly calls for one.142- If a view model exists, make it non-optional when possible.143- Pass dependencies to the view via `init`, then pass them into the view model in the view's `init`.144- Avoid `bootstrapIfNeeded` patterns.145146Example (Observation-based):147148```swift149@State private var viewModel: SomeViewModel150151init(dependency: Dependency) {152 _viewModel = State(initialValue: SomeViewModel(dependency: dependency))153}154```155156### 5) Observation usage157- For `@Observable` reference types, store them as `@State` in the root view.158- Pass observables down explicitly as needed; avoid optional state unless required.159160## Workflow1611621) Reorder the view to match the ordering rules.1632) Favor MV: move lightweight orchestration into the view using `@State`, `@Environment`, `@Query`, `task`, and `onChange`.1643) Ensure stable view structure: avoid top-level `if`-based branch swapping; move conditions to localized sections/modifiers.1654) If a view model exists, replace optional view models with a non-optional `@State` view model initialized in `init` by passing dependencies from the view.1665) Confirm Observation usage: `@State` for root `@Observable` view models, no redundant wrappers.1676) Keep behavior intact: do not change layout or business logic unless requested.168169## Notes170171- Prefer small, explicit helpers over large conditional blocks.172- Keep computed view builders below `body` and non-view computed vars above `init`.173- For MV-first guidance and rationale, see `references/mv-patterns.md`.174175## Large-view handling176177- When a SwiftUI view file exceeds ~300 lines, split it using extensions to group related helpers. Move async functions and helper functions into dedicated `private` extensions, separated with `// MARK: -` comments that describe their purpose (e.g., `// MARK: - Actions`, `// MARK: - Subviews`, `// MARK: - Helpers`). Keep the main `struct` focused on stored properties, init, and `body`, with view-building computed vars also grouped via marks when the file is long.