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.
When to Use
- When cleaning up a large SwiftUI view or splitting long
body implementations.
- When you need smaller subviews, explicit dependency injection, or better Observation usage.
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.
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.
Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
Source: sickn33/agentic-awesome-skills → skills/swiftui-view-refactor/SKILL.md
Also appears in: sickn33/agentic-awesome-skills/plugins/agentic-awesome-skills/skills/swiftui-view-refactor/SKILL.md, sickn33/agentic-awesome-skills/plugins/agentic-awesome-skills-claude/skills/swiftui-view-refactor/SKILL.md
1---2name: swiftui-view-refactor3description: "Refactor SwiftUI views into smaller components with stable, explicit data flow."4category: engineering-core5source_repo: sickn33/agentic-awesome-skills6source_path: "skills/swiftui-view-refactor/SKILL.md"7source_url: https://github.com/sickn33/agentic-awesome-skills/blob/HEAD/skills/swiftui-view-refactor/SKILL.md8metadata:9 source: https://skillmd.com/skills/sickn33/swiftui-view-refactor10---111213# SwiftUI View Refactor1415## Overview16Refactor 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.1718## When to Use19- When cleaning up a large SwiftUI view or splitting long `body` implementations.20- When you need smaller subviews, explicit dependency injection, or better Observation usage.2122## Core Guidelines2324### 1) View ordering (top → bottom)25- Enforce this ordering unless the existing file has a stronger local convention you must preserve.26- Environment27- `private`/`public` `let`28- `@State` / other stored properties29- computed `var` (non-view)30- `init`31- `body`32- computed view builders / other view helpers33- helper / async functions3435### 2) Default to MV, not MVVM36- Views should be lightweight state expressions and orchestration points, not containers for business logic.37- Favor `@State`, `@Environment`, `@Query`, `.task`, `.task(id:)`, and `onChange` before reaching for a view model.38- Inject services and shared models via `@Environment`; keep domain logic in services/models, not in the view body.39- Do not introduce a view model just to mirror local view state or wrap environment dependencies.40- If a screen is getting large, split the UI into subviews before inventing a new view model layer.4142### 3) Strongly prefer dedicated subview types over computed `some View` helpers43- Flag `body` properties that are longer than roughly one screen or contain multiple logical sections.44- Prefer extracting dedicated `View` types for non-trivial sections, especially when they have state, async work, branching, or deserve their own preview.45- Keep computed `some View` helpers rare and small. Do not build an entire screen out of `private var header: some View`-style fragments.46- Pass small, explicit inputs (data, bindings, callbacks) into extracted subviews instead of handing down the entire parent state.47- If an extracted subview becomes reusable or independently meaningful, move it to its own file.4849Prefer:5051```swift52var body: some View {53 List {54 HeaderSection(title: title, subtitle: subtitle)55 FilterSection(56 filterOptions: filterOptions,57 selectedFilter: $selectedFilter58 )59 ResultsSection(items: filteredItems)60 FooterSection()61 }62}6364private struct HeaderSection: View {65 let title: String66 let subtitle: String6768 var body: some View {69 VStack(alignment: .leading, spacing: 6) {70 Text(title).font(.title2)71 Text(subtitle).font(.subheadline)72 }73 }74}7576private struct FilterSection: View {77 let filterOptions: [FilterOption]78 @Binding var selectedFilter: FilterOption7980 var body: some View {81 ScrollView(.horizontal, showsIndicators: false) {82 HStack {83 ForEach(filterOptions, id: \.self) { option in84 FilterChip(option: option, isSelected: option == selectedFilter)85 .onTapGesture { selectedFilter = option }86 }87 }88 }89 }90}91```9293Avoid:9495```swift96var body: some View {97 List {98 header99 filters100 results101 footer102 }103}104105private var header: some View {106 VStack(alignment: .leading, spacing: 6) {107 Text(title).font(.title2)108 Text(subtitle).font(.subheadline)109 }110}111```112113### 3b) Extract actions and side effects out of `body`114- Do not keep non-trivial button actions inline in the view body.115- Do not bury business logic inside `.task`, `.onAppear`, `.onChange`, or `.refreshable`.116- Prefer calling small private methods from the view, and move real business logic into services/models.117- The body should read like UI, not like a view controller.118119```swift120Button("Save", action: save)121 .disabled(isSaving)122123.task(id: searchText) {124 await reload(for: searchText)125}126127private func save() {128 Task { await saveAsync() }129}130131private func reload(for searchText: String) async {132 guard !searchText.isEmpty else {133 results = []134 return135 }136 await searchService.search(searchText)137}138```139140### 4) Keep a stable view tree (avoid top-level conditional view swapping)141- Avoid `body` or computed views that return completely different root branches via `if/else`.142- Prefer a single stable base view with conditions inside sections/modifiers (`overlay`, `opacity`, `disabled`, `toolbar`, etc.).143- Root-level branch swapping causes identity churn, broader invalidation, and extra recomputation.144145Prefer:146147```swift148var body: some View {149 List {150 documentsListContent151 }152 .toolbar {153 if canEdit {154 editToolbar155 }156 }157}158```159160Avoid:161162```swift163var documentsListView: some View {164 if canEdit {165 editableDocumentsList166 } else {167 readOnlyDocumentsList168 }169}170```171172### 5) View model handling (only if already present or explicitly requested)173- Treat view models as a legacy or explicit-need pattern, not the default.174- Do not introduce a view model unless the request or existing code clearly calls for one.175- If a view model exists, make it non-optional when possible.176- Pass dependencies to the view via `init`, then create the view model in the view's `init`.177- Avoid `bootstrapIfNeeded` patterns and other delayed setup workarounds.178179Example (Observation-based):180181```swift182@State private var viewModel: SomeViewModel183184init(dependency: Dependency) {185 _viewModel = State(initialValue: SomeViewModel(dependency: dependency))186}187```188189### 6) Observation usage190- For `@Observable` reference types on iOS 17+, store them as `@State` in the owning view.191- Pass observables down explicitly; avoid optional state unless the UI genuinely needs it.192- If the deployment target includes iOS 16 or earlier, use `@StateObject` at the owner and `@ObservedObject` when injecting legacy observable models.193194## Workflow1951961. Reorder the view to match the ordering rules.1972. Remove inline actions and side effects from `body`; move business logic into services/models and keep only thin orchestration in the view.1983. Shorten long bodies by extracting dedicated subview types; avoid rebuilding the screen out of many computed `some View` helpers.1994. Ensure stable view structure: avoid top-level `if`-based branch swapping; move conditions to localized sections/modifiers.2005. If a view model exists or is explicitly required, replace optional view models with a non-optional `@State` view model initialized in `init`.2016. Confirm Observation usage: `@State` for root `@Observable` models on iOS 17+, legacy wrappers only when the deployment target requires them.2027. Keep behavior intact: do not change layout or business logic unless requested.203204## Notes205206- Prefer small, explicit view types over large conditional blocks and large computed `some View` properties.207- Keep computed view builders below `body` and non-view computed vars above `init`.208- A good SwiftUI refactor should make the view read top-to-bottom as data flow plus layout, not as mixed layout and imperative logic.209- For MV-first guidance and rationale, see `references/mv-patterns.md`.210211## Large-view handling212213When 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.214215## Limitations216- Use this skill only when the task clearly matches the scope described above.217- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.218- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.219220---221222**Source:** [`sickn33/agentic-awesome-skills`](https://github.com/sickn33/agentic-awesome-skills) → `skills/swiftui-view-refactor/SKILL.md`223224**Also appears in:** `sickn33/agentic-awesome-skills/plugins/agentic-awesome-skills/skills/swiftui-view-refactor/SKILL.md`, `sickn33/agentic-awesome-skills/plugins/agentic-awesome-skills-claude/skills/swiftui-view-refactor/SKILL.md`