본문으로 건너뛰기
Skillpedia
모바일 앱7.4k · #13251

swiftui-view-refactor

하는 일

이 스킬은 SwiftUI 뷰 코드를 읽고 관리하기 쉽도록 구조를 다시 짭니다. 크거나 복잡하게 뒤엉킨 뷰를 가진 iOS 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓SwiftUI 뷰 파일이 커져서 읽고 관리하기 어려울 때.
  • ✓뷰의 body가 너무 길어서 더 작은 부분으로 나눠야 할 때.
  • ✓뷰의 상태와 의존성을 일관된 방식으로 설정하고 싶을 때.

스킬 링크

https://github.com/steipete/agent-scripts/blob/main/skills/swiftui-view-refactor/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/steipete/agent-scripts/blob/main/skills/swiftui-view-refactor/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“이 SwiftUI 화면 파일이 너무 커요. 작은 뷰로 나누고 깔끔한 구조로 리팩터링해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트는 뷰의 속성과 코드에 일관된 순서를 적용하고, 큰 body는 하위 뷰로 나눕니다. 추가 뷰 모델보다 단순한 상태와 환경 주입을 선호합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

SwiftUI View Refactor

Attribution: copied from @Dimillian’s Dimillian/Skills (2025-12-31).

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.
자주 묻는 질문

각 화면에 뷰 모델을 추가하나요?

아닙니다. 스킬은 뷰는 단순하게 두고 모델이 비즈니스 로직을 담당하는 가벼운 패턴을 선호합니다.

뷰 파일에서 속성은 어디에 두나요?

환경 값을 먼저 두고 그다음 저장 속성을 두는 식으로, 정해진 순서에 따라 배치합니다.

도우미 기능은 언제 별도 뷰가 되나요?

상태를 가지거나 복잡한 분기가 있을 때, 또는 재사용 구조가 의미 있을 때입니다.

상세 정보

작성자의 원본 설명

SwiftUI view refactor/review: layout, DI, Observation, view models.

repo: steipete/agent-scripts

인기도

GitHub 스타
7.4k
순위
#13251
라이선스
MIT
업데이트
2026. 10. 30.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬