SwiftUI View Refactor
Overview
Refactor SwiftUI views toward small, explicit, stable view types. Default to vanilla SwiftUI: local state in the view, shared dependencies in the environment, business logic in services/models, and view models only when the request or existing code clearly requires one.
Core Guidelines
1) View ordering (top → bottom)
- Enforce this ordering unless the existing file has a stronger local convention you must preserve.
- Environment
private/public let
@State / other stored properties
- computed
var (non-view)
init
body
- computed view builders / other view helpers
- helper / async functions
2) Default to MV, not MVVM
- Views should be lightweight state expressions and orchestration points, not containers for business logic.
- Favor
@State, @Environment, @Query, .task, .task(id:), and onChange before reaching for a view model.
- Inject services and shared models via
@Environment; keep domain logic in services/models, not in the view body.
- Do not introduce a view model just to mirror local view state or wrap environment dependencies.
- If a screen is getting large, split the UI into subviews before inventing a new view model layer.
3) Strongly prefer dedicated subview types over computed some View helpers
- Flag
body properties that are longer than roughly one screen or contain multiple logical sections.
- Prefer extracting dedicated
View types for non-trivial sections, especially when they have state, async work, branching, or deserve their own preview.
- Keep computed
some View helpers rare and small. Do not build an entire screen out of private var header: some View-style fragments.
- Pass small, explicit inputs (data, bindings, callbacks) into extracted subviews instead of handing down the entire parent state.
- If an extracted subview becomes reusable or independently meaningful, move it to its own file.
Prefer:
var body: some View {
List {
HeaderSection(title: title, subtitle: subtitle)
FilterSection(
filterOptions: filterOptions,
selectedFilter: $selectedFilter
)
ResultsSection(items: filteredItems)
FooterSection()
}
}
private struct HeaderSection: View {
let title: String
let subtitle: String
var body: some View {
VStack(alignment: .leading, spacing: 6) {
Text(title).font(.title2)
Text(subtitle).font(.subheadline)
}
}
}
private struct FilterSection: View {
let filterOptions: [FilterOption]
@Binding var selectedFilter: FilterOption
var body: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(filterOptions, id: \.self) { option in
FilterChip(option: option, isSelected: option == selectedFilter)
.onTapGesture { selectedFilter = option }
}
}
}
}
}
Avoid:
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)
}
}
3b) Extract actions and side effects out of body
- Do not keep non-trivial button actions inline in the view body.
- Do not bury business logic inside
.task, .onAppear, .onChange, or .refreshable.
- Prefer calling small private methods from the view, and move real business logic into services/models.
- The body should read like UI, not like a view controller.
Button("Save", action: save)
.disabled(isSaving)
.task(id: searchText) {
await reload(for: searchText)
}
private func save() {
Task { await saveAsync() }
}
private func reload(for searchText: String) async {
guard !searchText.isEmpty else {
results = []
return
}
await searchService.search(searchText)
}
4) Keep a stable view tree (avoid top-level conditional view swapping)
- Avoid
body or computed views that return completely different root branches via if/else.
- Prefer a single stable base view with conditions inside sections/modifiers (
overlay, opacity, disabled, toolbar, etc.).
- Root-level branch swapping causes identity churn, broader invalidation, and extra recomputation.
Prefer:
var body: some View {
List {
documentsListContent
}
.toolbar {
if canEdit {
editToolbar
}
}
}
Avoid:
var documentsListView: some View {
if canEdit {
editableDocumentsList
} else {
readOnlyDocumentsList
}
}
5) View model handling (only if already present or explicitly requested)
- Treat view models as a legacy or explicit-need pattern, not the default.
- 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 create the view model in the view's init.
- Avoid
bootstrapIfNeeded patterns and other delayed setup workarounds.
Example (Observation-based):
@State private var viewModel: SomeViewModel
init(dependency: Dependency) {
_viewModel = State(initialValue: SomeViewModel(dependency: dependency))
}
6) Observation usage
- For
@Observable reference types on iOS 17+, store them as @State in the owning view.
- Pass observables down explicitly; avoid optional state unless the UI genuinely needs it.
- If the deployment target includes iOS 16 or earlier, use
@StateObject at the owner and @ObservedObject when injecting legacy observable models.
Workflow
- Reorder the view to match the ordering rules.
- Remove inline actions and side effects from
body; move business logic into services/models and keep only thin orchestration in the view.
- Shorten long bodies by extracting dedicated subview types; avoid rebuilding the screen out of many computed
some View helpers.
- Ensure stable view structure: avoid top-level
if-based branch swapping; move conditions to localized sections/modifiers.
- If a view model exists or is explicitly required, replace optional view models with a non-optional
@State view model initialized in init.
- Confirm Observation usage:
@State for root @Observable models on iOS 17+, legacy wrappers only when the deployment target requires them.
- Keep behavior intact: do not change layout or business logic unless requested.
Notes
- Prefer small, explicit view types over large conditional blocks and large computed
some View properties.
- Keep computed view builders below
body and non-view computed vars above init.
- A good SwiftUI refactor should make the view read top-to-bottom as data flow plus layout, not as mixed layout and imperative logic.
- For MV-first guidance and rationale, see
references/mv-patterns.md.
- In addition to the references above, use web search to consult current Apple Developer documentation when SwiftUI APIs, Observation behavior, or platform guidance may have changed.
Large-view handling
When a SwiftUI view file exceeds ~300 lines, split it aggressively. Extract meaningful sections into dedicated View types instead of hiding complexity in many computed properties. Use private extensions with // MARK: - comments for actions and helpers, but do not treat extensions as a substitute for breaking a giant screen into smaller view types. If an extracted subview
is reused or
independently meaningful, move it into its own file.
1---2name: swiftui-view-refactor3description: Refactor SwiftUI view files into stable, testable structure. Use when splitting large views, tightening data flow, or cleaning Observation ownership.4---5
6# SwiftUI View Refactor
7
8## Overview
9
10Refactor SwiftUI views toward small, explicit, stable view types. Default to vanilla SwiftUI: local state in the view, shared dependencies in the environment, business logic in services/models, and view models only when the request or existing code clearly requires one.
11
12## Core Guidelines
13
14### 1) View ordering (top → bottom)
15
16- Enforce this ordering unless the existing file has a stronger local convention you must preserve.
17- Environment
18- `private`/`public` `let`
19- `@State` / other stored properties
20- computed `var` (non-view)
21- `init`
22- `body`
23- computed view builders / other view helpers
24- helper / async functions
25
26### 2) Default to MV, not MVVM
27
28- Views should be lightweight state expressions and orchestration points, not containers for business logic.
29- Favor `@State`, `@Environment`, `@Query`, `.task`, `.task(id:)`, and `onChange` before reaching for a view model.
30- Inject services and shared models via `@Environment`; keep domain logic in services/models, not in the view body.
31- Do not introduce a view model just to mirror local view state or wrap environment dependencies.
32- If a screen is getting large, split the UI into subviews before inventing a new view model layer.
33
34### 3) Strongly prefer dedicated subview types over computed `some View` helpers
35
36- Flag `body` properties that are longer than roughly one screen or contain multiple logical sections.
37- Prefer extracting dedicated `View` types for non-trivial sections, especially when they have state, async work, branching, or deserve their own preview.
38- Keep computed `some View` helpers rare and small. Do not build an entire screen out of `private var header: some View`-style fragments.
39- Pass small, explicit inputs (data, bindings, callbacks) into extracted subviews instead of handing down the entire parent state.
40- If an extracted subview becomes reusable or independently meaningful, move it to its own file.
41
42Prefer:
43
44```swift
45var body: some View {
46 List {
47 HeaderSection(title: title, subtitle: subtitle)
48 FilterSection(
49 filterOptions: filterOptions,
50 selectedFilter: $selectedFilter
51 )
52 ResultsSection(items: filteredItems)
53 FooterSection()
54 }
55}
56
57private struct HeaderSection: View {
58 let title: String
59 let subtitle: String
60
61 var body: some View {
62 VStack(alignment: .leading, spacing: 6) {
63 Text(title).font(.title2)
64 Text(subtitle).font(.subheadline)
65 }
66 }
67}
68
69private struct FilterSection: View {
70 let filterOptions: [FilterOption]
71 @Binding var selectedFilter: FilterOption
72
73 var body: some View {
74 ScrollView(.horizontal, showsIndicators: false) {
75 HStack {
76 ForEach(filterOptions, id: \.self) { option in
77 FilterChip(option: option, isSelected: option == selectedFilter)
78 .onTapGesture { selectedFilter = option }
79 }
80 }
81 }
82 }
83}
84```
85
86Avoid:
87
88```swift
89var body: some View {
90 List {
91 header
92 filters
93 results
94 footer
95 }
96}
97
98private var header: some View {
99 VStack(alignment: .leading, spacing: 6) {
100 Text(title).font(.title2)
101 Text(subtitle).font(.subheadline)
102 }
103}
104```
105
106### 3b) Extract actions and side effects out of `body`
107
108- Do not keep non-trivial button actions inline in the view body.
109- Do not bury business logic inside `.task`, `.onAppear`, `.onChange`, or `.refreshable`.
110- Prefer calling small private methods from the view, and move real business logic into services/models.
111- The body should read like UI, not like a view controller.
112
113```swift
114Button("Save", action: save)
115 .disabled(isSaving)
116
117.task(id: searchText) {
118 await reload(for: searchText)
119}
120
121private func save() {
122 Task { await saveAsync() }
123}
124
125private func reload(for searchText: String) async {
126 guard !searchText.isEmpty else {
127 results = []
128 return
129 }
130 await searchService.search(searchText)
131}
132```
133
134### 4) Keep a stable view tree (avoid top-level conditional view swapping)
135
136- Avoid `body` or computed views that return completely different root branches via `if/else`.
137- Prefer a single stable base view with conditions inside sections/modifiers (`overlay`, `opacity`, `disabled`, `toolbar`, etc.).
138- Root-level branch swapping causes identity churn, broader invalidation, and extra recomputation.
139
140Prefer:
141
142```swift
143var body: some View {
144 List {
145 documentsListContent
146 }
147 .toolbar {
148 if canEdit {
149 editToolbar
150 }
151 }
152}
153```
154
155Avoid:
156
157```swift
158var documentsListView: some View {
159 if canEdit {
160 editableDocumentsList
161 } else {
162 readOnlyDocumentsList
163 }
164}
165```
166
167### 5) View model handling (only if already present or explicitly requested)
168
169- Treat view models as a legacy or explicit-need pattern, not the default.
170- Do not introduce a view model unless the request or existing code clearly calls for one.
171- If a view model exists, make it non-optional when possible.
172- Pass dependencies to the view via `init`, then create the view model in the view's `init`.
173- Avoid `bootstrapIfNeeded` patterns and other delayed setup workarounds.
174
175Example (Observation-based):
176
177```swift
178@State private var viewModel: SomeViewModel
179
180init(dependency: Dependency) {
181 _viewModel = State(initialValue: SomeViewModel(dependency: dependency))
182}
183```
184
185### 6) Observation usage
186
187- For `@Observable` reference types on iOS 17+, store them as `@State` in the owning view.
188- Pass observables down explicitly; avoid optional state unless the UI genuinely needs it.
189- If the deployment target includes iOS 16 or earlier, use `@StateObject` at the owner and `@ObservedObject` when injecting legacy observable models.
190
191## Workflow
192
1931. Reorder the view to match the ordering rules.
1942. Remove inline actions and side effects from `body`; move business logic into services/models and keep only thin orchestration in the view.
1953. Shorten long bodies by extracting dedicated subview types; avoid rebuilding the screen out of many computed `some View` helpers.
1964. Ensure stable view structure: avoid top-level `if`-based branch swapping; move conditions to localized sections/modifiers.
1975. If a view model exists or is explicitly required, replace optional view models with a non-optional `@State` view model initialized in `init`.
1986. Confirm Observation usage: `@State` for root `@Observable` models on iOS 17+, legacy wrappers only when the deployment target requires them.
1997. Keep behavior intact: do not change layout or business logic unless requested.
200
201## Notes
202
203- Prefer small, explicit view types over large conditional blocks and large computed `some View` properties.
204- Keep computed view builders below `body` and non-view computed vars above `init`.
205- A good SwiftUI refactor should make the view read top-to-bottom as data flow plus layout, not as mixed layout and imperative logic.
206- For MV-first guidance and rationale, see `references/mv-patterns.md`.
207- In addition to the references above, use web search to consult current Apple Developer documentation when SwiftUI APIs, Observation behavior, or platform guidance may have changed.
208
209## Large-view handling
210
211When a SwiftUI view file exceeds ~300 lines, split it aggressively. Extract meaningful sections into dedicated `View` types instead of hiding complexity in many computed properties. Use `private` extensions with `// MARK: -` comments for actions and helpers, but do not treat extensions as a substitute for breaking a giant screen into smaller view types. If an extracted subview
212is reused or
213independently meaningful, move it into its own file.