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/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)
}
}
}
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.
- 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---5
6# SwiftUI View Refactor
7
8## Overview
9Apply 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.
10
11## Core Guidelines
12
13### 1) View ordering (top → bottom)
14- Environment
15- `private`/`public` `let`
16- `@State` / other stored properties
17- computed `var` (non-view)
18- `init`
19- `body`
20- computed view builders / other view helpers
21- helper / async functions
22
23### 2) Prefer MV (Model-View) patterns
24- Default to MV: Views are lightweight state expressions; models/services own business logic.
25- Favor `@State`, `@Environment`, `@Query`, and `task`/`onChange` for orchestration.
26- Inject services and shared models via `@Environment`; keep views small and composable.
27- Split large views into subviews rather than introducing a view model.
28
29### 3) Split large bodies and view properties
30- If `body` grows beyond a screen or has multiple logical sections, split it into smaller subviews.
31- Extract large computed view properties (`var header: some View { ... }`) into dedicated `View` types when they carry state or complex branching.
32- 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.
33- Prefer passing small inputs (data, bindings, callbacks) over reusing the entire parent view state.
34
35Example (extracting a section):
36
37```swift
38var body: some View {
39 VStack(alignment: .leading, spacing: 16) {
40 HeaderSection(title: title, isPinned: isPinned)
41 DetailsSection(details: details)
42 ActionsSection(onSave: onSave, onCancel: onCancel)
43 }
44}
45```
46
47Example (long body → shorter body + computed views in the same file):
48
49```swift
50var body: some View {
51 List {
52 header
53 filters
54 results
55 footer
56 }
57}
58
59private var header: some View {
60 VStack(alignment: .leading, spacing: 6) {
61 Text(title).font(.title2)
62 Text(subtitle).font(.subheadline)
63 }
64}
65
66private var filters: some View {
67 ScrollView(.horizontal, showsIndicators: false) {
68 HStack {
69 ForEach(filterOptions, id: \.self) { option in
70 FilterChip(option: option, isSelected: option == selectedFilter)
71 .onTapGesture { selectedFilter = option }
72 }
73 }
74 }
75}
76```
77
78Example (extracting a complex computed view):
79
80```swift
81private var header: some View {
82 HeaderSection(title: title, subtitle: subtitle, status: status)
83}
84
85private struct HeaderSection: View {
86 let title: String
87 let subtitle: String?
88 let status: Status
89
90 var body: some View {
91 VStack(alignment: .leading, spacing: 4) {
92 Text(title).font(.headline)
93 if let subtitle { Text(subtitle).font(.subheadline) }
94 StatusBadge(status: status)
95 }
96 }
97}
98```
99
100### 4) View model handling (only if already present)
101- Do not introduce a view model unless the request or existing code clearly calls for one.
102- If a view model exists, make it non-optional when possible.
103- Pass dependencies to the view via `init`, then pass them into the view model in the view's `init`.
104- Avoid `bootstrapIfNeeded` patterns.
105
106Example (Observation-based):
107
108```swift
109@State private var viewModel: SomeViewModel
110
111init(dependency: Dependency) {
112 _viewModel = State(initialValue: SomeViewModel(dependency: dependency))
113}
114```
115
116### 5) Observation usage
117- For `@Observable` reference types, store them as `@State` in the root view.
118- Pass observables down explicitly as needed; avoid optional state unless required.
119
120## Workflow
121
1221) Reorder the view to match the ordering rules.
1232) Favor MV: move lightweight orchestration into the view using `@State`, `@Environment`, `@Query`, `task`, and `onChange`.
1243) 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.
1254) Confirm Observation usage: `@State` for root `@Observable` view models, no redundant wrappers.
1265) Keep behavior intact: do not change layout or business logic unless requested.
127
128## Notes
129
130- Prefer small, explicit helpers over large conditional blocks.
131- Keep computed view builders below `body` and non-view computed vars above `init`.
132- For MV-first guidance and rationale, see `references/mv-patterns.md`.
133
134## Large-view handling
135
136- 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.