SW

swiftui-view-refactor

Standardize SwiftUI code structure, property ordering, and state management patterns.

Install

mkdir -p .claude/skills/swiftui-view-refactor-hot666666 && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/14220" && unzip -o skill.zip -d .claude/skills/swiftui-view-refactor-hot666666 && rm skill.zip

Installs to .claude/skills/swiftui-view-refactor-hot666666

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

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.
308 chars✓ has a “when” triggerlonger than Claude Code's old 250-char listing cap (fine on current versions)
Intermediate

Key capabilities

  • →Reorder SwiftUI view properties for consistent structure
  • →Apply Model-View (MV) patterns to SwiftUI views
  • →Split large view bodies into smaller subviews or computed view properties
  • →Handle view models as non-optional when possible
  • →Ensure correct usage of `@Observable` state

How it works

The skill refactors SwiftUI view files by reordering properties, applying MV patterns, splitting large view bodies, and ensuring correct view model and Observation usage.

Inputs & outputs

You give it
SwiftUI view files with inconsistent structure, large bodies, or unclear dependency handling
You get back
Refactored SwiftUI view files with consistent ordering, MV patterns, and proper state handling

When to use swiftui-view-refactor

  • →Clean up a large view body
  • →Implement dependency injection for views
  • →Standardize SwiftUI view property ordering
  • →Transition to Observable state

About this skill

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

  1. Reorder the view to match the ordering rules.
  2. Favor MV: move lightweight orchestration into the view using @State, @Environment, @Query, task, and onChange.
  3. 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.
  4. Confirm Observation usage: @State for root @Observable view models, no redundant wrappers.
  5. 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.

When not to use it

  • →When the request is to introduce a view model without clear necessity
  • →When the focus is on business logic rather than view structure
  • →When the view is already small and well-structured

Limitations

  • →The skill does not introduce a view model unless explicitly requested or clearly present
  • →The skill focuses on view structure and state handling, not business logic changes
  • →The skill recommends splitting large view files exceeding ~300 lines

How it compares

This skill provides a structured approach to refactoring SwiftUI views for consistency and maintainability, focusing on explicit ordering and MV patterns, unlike ad-hoc code cleanup.

Compared to similar skills

swiftui-view-refactor side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
swiftui-view-refactor (this skill)08moNo flagsIntermediate
feature-toggle-developer18moReviewIntermediate
swiftdata-pro05moReviewIntermediate
swift-coding02moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

feature-toggle-developer

anyproto

Guides systematic removal of feature toggles from the codebase with automated cleanup detection. Use when removing feature flags, enabling toggles permanently, or cleaning up unused code after toggle removal.

14

swiftdata-pro

sobchak-security

Writes, reviews, and improves SwiftData code using modern APIs and best practices. Use when reading, writing, or reviewing projects that use SwiftData.

00

swift-coding

Dynokostya

Apply when writing or editing Swift (.swift) files. Behavioral corrections for error handling, concurrency, memory management, type safety, protocol-oriented design, security defaults, and common antipatterns. Project conventions always override these defaults.

00

swift-concurrency

AvdLee

Expert guidance on Swift Concurrency best practices, patterns, and implementation. Use when developers mention: (1) Swift Concurrency, async/await, actors, or tasks, (2) "use Swift Concurrency" or "modern concurrency patterns", (3) migrating to Swift 6, (4) data races or thread safety issues, (5) refactoring closures to async/await, (6) @MainActor, Sendable, or actor isolation, (7) concurrent code architecture or performance optimization, (8) concurrency-related linter warnings (SwiftLint or similar; e.g. async_without_await, Sendable/actor isolation/MainActor lint).

433

swift-concurrency-expert

Dimillian

Swift Concurrency review and remediation for Swift 6.2+. Use when asked to review Swift Concurrency usage, improve concurrency compliance, or fix Swift concurrency compiler errors in a feature or file.

420

ios-dev-guidelines

anyproto

Context-aware routing to Swift/iOS development patterns, architecture, and best practices. Use when working with .swift files, ViewModels, Coordinators, refactoring, or discussing Swift/SwiftUI patterns.

37

Search skills

Search the agent skills registry