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