Community程式設計與開發github.com

steipete/swiftui-view-refactor

SwiftUI 檢視重構/審查:佈局、依賴注入、Observation、檢視模型。

swiftui-view-refactor 是什麼?

此技能為 SwiftUI 開發者提供一套結構化的檢視重構與審查準則,專注於提升程式碼一致性與可維護性。它涵蓋了檢視屬性的標準排序規則(從環境變數到輔助函數),並強烈推薦採用 Model-View (MV) 模式,將檢視保持輕量,將商業邏輯委託給模型與服務。技能詳細說明了何時應將大型 body 或複雜的 computed view 屬性拆分為子檢視,並提供具體的程式碼範例。對於已存在的檢視模型,它要求使用 `@State` 與 `@Observable` 確保非可選型別,並在 `init` 中透過依賴注入傳遞,避免 `bootstrapIfNeeded` 等反模式。此技能主要適用於 Xcode 與 Swift 專案,能幫助開發團隊統一 SwiftUI 開發風格,減少技術債與潛在的觀測性問題。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/steipete/agent-scripts/tree/main/skills/swiftui-view-refactor

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

SwiftUI 檢視重構

來源:取自 @Dimillian 的 Dimillian/Skills (2025-12-31)。

概述

為 SwiftUI 檢視套用一致的結構與依賴模式,重點關注排序、Model-View (MV) 模式、謹慎的檢視模型處理,以及正確的 Observation 使用方式。

核心指導方針

1) 檢視屬性排序(由上至下)

  • Environment
  • private/public let
  • @State / 其他儲存屬性
  • computed var(非檢視)
  • init
  • body
  • computed 檢視建構器 / 其他檢視輔助屬性
  • 輔助 / 非同步函數

2) 偏好 MV (Model-View) 模式

  • 預設使用 MV:檢視是輕量的狀態表達式;模型/服務擁有商業邏輯。
  • 優先使用 @State、@Environment、@Query 以及 task/onChange 進行協調。
  • 透過 @Environment 注入服務與共享模型;保持檢視小巧且可組合。
  • 將大型檢視拆分成子檢視,而非引入檢視模型。

3) 拆分大型 body 與檢視屬性

  • 若 body 超出一個畫面或包含多個邏輯區塊,請將其拆分成較小的子檢視。
  • 當大型 computed 檢視屬性(如 var header: some View { ... })攜帶狀態或複雜分支時,將其提取為專用的 View 型別。
  • 可以將相關的子檢視作為 computed 檢視屬性保留在同一個檔案中;只有在結構上合理或預期要重複使用時,才將其提取為獨立的 View 結構。
  • 偏好傳遞小型的輸入資料(資料、綁定、回呼),而非重複使用整個父檢視的狀態。

範例(提取區塊):

var body: some View {
    VStack(alignment: .leading, spacing: 16) {
        HeaderSection(title: title, isPinned: isPinned)
        DetailsSection(details: details)
        ActionsSection(onSave: onSave, onCancel: onCancel)
    }
}

範例(長 body → 較短的 body + 同檔案中的 computed 檢視):

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 }
            }
        }
    }
}

範例(提取複雜的 computed 檢視):

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) 檢視模型處理(僅在已存在時)

  • 除非需求或現有程式碼明確要求,否則請勿引入檢視模型。
  • 如果檢視模型已存在,請儘可能使其非可選。
  • 透過 init 將依賴傳遞給檢視,然後在檢視的 init 中將它們傳遞給檢視模型。
  • 避免使用 bootstrapIfNeeded 模式。

範例(基於 Observation):

@State private var viewModel: SomeViewModel

init(dependency: Dependency) {
    _viewModel = State(initialValue: SomeViewModel(dependency: dependency))
}

5) Observation 使用方式

  • 對於 @Observable 參考型別,請將其作為 @State 儲存在根檢視中。
  • 根據需要顯式向下傳遞可觀察物件;除非必要,否則避免使用可選狀態。

工作流程

  1. 重新排序檢視以符合排序規則。
  2. 偏好 MV:使用 @State、@Environment、@Query、task 與 onChange 將輕量協調邏輯移入檢視。
  3. 如果存在檢視模型,請將可選檢視模型替換為在 init 中透過從檢視傳遞依賴而初始化的非可選 @State 檢視模型。
  4. 確認 Observation 使用方式:根 @Observable 檢視模型使用 @State,無冗餘包裝器。
  5. 保持行為不變:除非要求,否則不要更改佈局或商業邏輯。

注意事項

  • 偏好小型顯式輔助屬性,而非大型條件區塊。
  • 將 computed 檢視建構器保持在 body 下方,非檢視的 computed var 保持在 init 上方。
  • 關於 MV 優先指導與原理,請參閱 references/mv-patterns.md。

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

steipete/agent-transcript

GitHub PR/issue agent transcripts: redact, preview, and insert safely.

steipete/beeper

Beeper cache: contact hints, room lookup, WhatsApp/iMessage traces, FTS.

steipete/browser-use

Existing Chrome automation: Chrome plugin first, mcporter fallback.

steipete/clawsweeper-status

ClawSweeper status: URLs, workflow health, active workers, ops snapshot.

steipete/clickclack

ClickClack ops: chat app, Hetzner deploy, DNS/docs/app, Docker rollout.

steipete/cloudflare-registrar

Cloudflare Registrar: domain availability, prices, registration via mcporter.

steipete/codex-debugging

Codex debugging: codex-rs core/tui/exec/cli/app-server/config.

steipete/create-cli

CLI UX/spec: args, flags, help, output, errors, config, dry-run.

steipete/discord-clawd

Discord-backed OpenClaw agent/session relay; not archive search.

steipete/domain-dns-ops

DNS/domain ops: registrars, zones, redirects, DNS/HTTP verify, manager truth.

steipete/frontend-design

Frontend UI: pages, apps, components, polished non-generic design.

steipete/github-author-context

GitHub contributor context: identity, activity, trust, company/team signal.

steipete/github-cache-hygiene

GitHub quota/cache hygiene: gh, ghx, xcache, gitcrawl, mirrors, limits.

steipete/github-deep-review

GitHub deep review: bugs, PRs, best fix, stale-or-real, read code first.

steipete/github-project-triage

GitHub issue/PR triage: queues, CI, blockers, risk, proof, next actions.

steipete/hopper-debugger

Hopper debugging: macOS/iOS binaries, ObjC/Swift symbols, dyld, LLDB.

steipete/instruments-profiling

Instruments/xctrace profiling: macOS/iOS traces, binaries, args, exports.

steipete/mac-maintenance

Mac upkeep: brew update/upgrade, pull clean repos, empty Trash.

steipete/maintainer-orchestrator

Open-source maintainer orchestration: Codex app workers, work recovery, dependencies, vision, releases.

steipete/markdown-converter

Markdown conversion: PDF, Office, HTML, data, OCR, audio, ZIP, YouTube.

相關技能