Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

swiftui-view-refactor

БесплатноБез исполняемых скриптовНе проверен

Restructures an existing SwiftUI view without changing what the user sees: splits an oversized body into small view types with narrow inputs, moves actions…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

SwiftUI View Refactor

Overview

A SwiftUI view grows by accretion: one more section in body, one more flag, one more closure with a network call in it. The result still works, but nobody can change it safely, previews stop being useful, and every state change recomputes the whole screen. Refactoring it means changing the structure while the pixels and the behaviour stay the same. In SwiftUI that takes care, because structure is behaviour: a view's position in the tree is its identity, and moving a view, a @State property or a .task can reset state or change when work runs. This skill gives a fixed order of small moves, the checks that keep behaviour intact, and the form of the final report.

Instructions

1. Agree the boundary and set a safety net

  • State the rule to the user: structure changes only. Bugs and design problems you notice are listed in the report, not fixed, unless they ask.
  • Build the target first. A refactor that starts from a red build cannot be verified.
  • Find the deployment target (it decides whether @Observable is available) and whether the project already has conventions for file layout, naming and state. Match them.
  • Make sure the view has a #Preview for each state it can show (loaded, empty, error, busy). If there are none, add them before changing anything: they are the only quick way to see that nothing moved. Keep accessibility identifiers as they are, because UI tests depend on them.

2. Map the view before touching it

Write a short inventory. It decides where the cuts go.

CheckoutView.swift: 212 lines, body 148 lines
Stored:   @ObservedObject cart: CartStore; @State promo, isPlacing, showError, errorText
Sections: lines list (reads cart.lines) | promo row (reads/writes promo, writes cart.discount)
          | total (reads cart.lines, cart.discount) | place-order button (reads isPlacing)
Effects:  Task in button action (network, mutates cart); alert bound to showError
Smells:   price maths in body; promo rule in a closure; AnyView in the button label

3. Apply the moves in this order

Each step is one kind of change. Build and look at the previews after each one.

Step A: name the actions. Replace multi-line closures in body (button actions, .task, .onChange, .refreshable) with calls to private methods on the same view. Nothing else moves, so this step cannot change behaviour, and body becomes readable.

Step B: move logic that is not about display out of the view. Calculations, validation rules, formatting decisions and network calls go to the model or a service type, where they can be unit-tested without SwiftUI. The view keeps only the thin method that calls them and updates view state.

Step C: extract sections into view types. For each section in the inventory create a struct conforming to View:

  • Give it the least it needs: values (let), bindings (@Binding) for what it edits, closures for what it triggers. Not the parent's whole model, unless it really uses most of it.
  • Extract leaves first, then the containers around them.
  • Keep it private in the same file until something else needs it; move it to its own file when it is reused or the file is still too long.
  • A computed property or @ViewBuilder function is enough for a fragment of a few lines with no state of its own. Prefer a type when the section has its own state or async work, deserves a preview, or reads data the rest of the screen does not: a separate view type is updated independently, so narrowing its inputs also narrows what SwiftUI recomputes.

Step D: repair the structure.

Found Change to Why
AnyView used to return different views @ViewBuilder, if/switch, or a generic parameter Type erasure hides the structure SwiftUI uses for identity and diffing
The same view in both branches of an if, differing in modifiers One view with conditional modifier values (.opacity(isLocked ? 0.6 : 1), .disabled(isLocked)) Each branch is a different identity; switching destroys the view's state and animates as a removal and insertion
Several Booleans driving mutually exclusive sheets or alerts One optional enum with sheet(item:) Removes impossible combinations
A child copying a parent's value into its own @State @Binding or a plain let Two sources of truth drift apart
Model built in init with State(initialValue:) or set in onAppear behind an optional @State private var model = Model() when it needs no inputs; otherwise receive the model from the parent, or create it in .task State storage is created once per view identity; later init arguments are ignored, which surprises readers
Values derived in body several times A computed property on the model, or one let at the top of body One definition, testable

Step E: migrate observation (only if asked or agreed, iOS 17+).

Before After
class Store: ObservableObject
Полный SKILL.md на GitHub

Установить swiftui-view-refactor в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл swiftui-view-refactor?

Restructures an existing SwiftUI view without changing what the user sees: splits an oversized body into small view types with narrow inputs, moves actions and business logic out of the view, replaces type erasure and duplicated branches, fixes state ownership, and migrates ObservableObject models to the Observable macro. Works in small steps that each build, and reports what moved and what could behave differently. Use when the user says "clean up this SwiftUI view", "this body is 300 lines", "split this view into subviews", "get the logic out of the view", "migrate to @Observable", "remove the AnyViews", or asks for a refactor of a SwiftUI file with no feature change.

Как установить скилл swiftui-view-refactor?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл swiftui-view-refactor запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить swiftui-view-refactor с