Communitygithub.com

SwiftUI 模式

SwiftUI 架構模式,包含 @Observable 狀態管理、視圖組合、導航、效能最佳化,以及現代 iOS/macOS UI 最佳實踐。在建立或審查 SwiftUI 視圖、@Observable 狀態、導航或渲染效能時使用。

SwiftUI 模式 是什麼?

此技能提供一套完整的現代 SwiftUI 開發模式,著重於使用 `@Observable` 巨集取代傳統的 `ObservableObject`,以實現精細的屬性級別變更追蹤,減少不必要的視圖重新渲染。它涵蓋了從狀態管理(`@State`、`@Binding`、`@Bindable`)到視圖組合(提取子視圖、`ViewModifier`)、型別安全導航(`NavigationStack` 搭配 `NavigationPath`)以及效能最佳化(惰性容器、穩定識別碼、`Equatable` 遵循)的關鍵主題。此技能適用於所有 Apple 平台(iOS、macOS、watchOS、tvOS)上的 SwiftUI 開發。透過遵循這些模式,開發者可以建立更具可維護性、高效能且現代化的宣告式 UI,並避免 `ObservableObject`、`AnyView` 或不當的 `body` 屬性中執行非同步工作等常見反模式。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/swiftui-patterns

在你喜歡的 AI 中提問

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

說明文件

SwiftUI 模式 是做什麼的?

現代 SwiftUI 模式,用於在 Apple 平台上建立宣告式、高效能的使用者介面。涵蓋 Observation 框架、視圖組合、型別安全導航與效能最佳化。

何時啟用

  • 建立 SwiftUI 視圖並管理狀態(@State、@Observable、@Binding)
  • 使用 NavigationStack 設計導航流程
  • 建構視圖模型與資料流程
  • 針對列表與複雜佈局最佳化渲染效能
  • 在 SwiftUI 中使用環境值與依賴注入

狀態管理

屬性包裝器選擇

選擇最符合需求的簡單包裝器:

包裝器使用情境
@State視圖區域的數值型別(切換開關、表單欄位、頁面呈現)
@Binding對父視圖 @State 的雙向參考
@Observable class + @State擁有含多個屬性的模型
@Observable class(無包裝器)從父視圖傳入的唯讀參考
@Bindable對 @Observable 屬性的雙向綁定
@Environment透過 .environment() 注入的共享依賴

@Observable ViewModel

使用 @Observable(而非 ObservableObject)— 它會追蹤屬性層級的變更,使 SwiftUI 僅重新渲染讀取該屬性的視圖:

@Observable
final class ItemListViewModel {
    private(set) var items: [Item] = []
    private(set) var isLoading = false
    var searchText = ""

    private let repository: any ItemRepository

    init(repository: any ItemRepository = DefaultItemRepository()) {
        self.repository = repository
    }

    func load() async {
        isLoading = true
        defer { isLoading = false }
        items = (try? await repository.fetchAll()) ?? []
    }
}

使用 ViewModel 的視圖

struct ItemListView: View {
    @State private var viewModel: ItemListViewModel

    init(viewModel: ItemListViewModel = ItemListViewModel()) {
        _viewModel = State(initialValue: viewModel)
    }

    var body: some View {
        List(viewModel.items) { item in
            ItemRow(item: item)
        }
        .searchable(text: $viewModel.searchText)
        .overlay { if viewModel.isLoading { ProgressView() } }
        .task { await viewModel.load() }
    }
}

環境注入

以 @Environment 取代 @EnvironmentObject:

// 注入
ContentView()
    .environment(authManager)

// 使用
struct ProfileView: View {
    @Environment(AuthManager.self) private var auth

    var body: some View {
        Text(auth.currentUser?.name ?? "訪客")
    }
}

視圖組合

提取子視圖以限制無效化

將視圖拆分為小型、專注的結構體。當狀態變更時,僅有讀取該狀態的子視圖會重新渲染:

struct OrderView: View {
    @State private var viewModel = OrderViewModel()

    var body: some View {
        VStack {
            OrderHeader(title: viewModel.title)
            OrderItemList(items: viewModel.items)
            OrderTotal(total: viewModel.total)
        }
    }
}

使用 ViewModifier 進行可重用樣式設定

struct CardModifier: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding()
            .background(.regularMaterial)
            .clipShape(RoundedRectangle(cornerRadius: 12))
    }
}

extension View {
    func cardStyle() -> some View {
        modifier(CardModifier())
    }
}

導航

型別安全的 NavigationStack

使用 NavigationStack 搭配 NavigationPath 進行程式化、型別安全的路由:

@Observable
final class Router {
    var path = NavigationPath()

    func navigate(to destination: Destination) {
        path.append(destination)
    }

    func popToRoot() {
        path = NavigationPath()
    }
}

enum Destination: Hashable {
    case detail(Item.ID)
    case settings
    case profile(User.ID)
}

struct RootView: View {
    @State private var router = Router()

    var body: some View {
        NavigationStack(path: $router.path) {
            HomeView()
                .navigationDestination(for: Destination.self) { dest in
                    switch dest {
                    case .detail(let id): ItemDetailView(itemID: id)
                    case .settings: SettingsView()
                    case .profile(let id): ProfileView(userID: id)
                    }
                }
        }
        .environment(router)
    }
}

效能

對大型集合使用惰性容器

LazyVStack 和 LazyHStack 僅在可見時才建立視圖:

ScrollView {
    LazyVStack(spacing: 8) {
        ForEach(items) { item in
            ItemRow(item: item)
        }
    }
}

穩定的識別碼

在 ForEach 中始終使用穩定、唯一的 ID — 避免使用陣列索引:

// 使用 Identifiable 遵循或明確的 id
ForEach(items, id: \.stableID) { item in
    ItemRow(item: item)
}

避免在 body 中進行昂貴操作

  • 絕不在 body 內部執行 I/O、網路請求或大量計算
  • 使用 .task {} 進行非同步工作 — 當視圖消失時它會自動取消
  • 在滾動視圖中謹慎使用 .sensoryFeedback() 和 .geometryGroup()
  • 盡量減少列表中的 .shadow()、.blur() 和 .mask() — 它們會觸發離屏渲染

Equatable 遵循

對於主體昂貴的視圖,遵循 Equatable 以跳過不必要的重新渲染:

struct ExpensiveChartView: View, Equatable {
    let dataPoints: [DataPoint] // DataPoint 必須遵循 Equatable

    static func == (lhs: Self, rhs: Self) -> Bool {
        lhs.dataPoints == rhs.dataPoints
    }

    var body: some View {
        // 複雜的圖表渲染
    }
}

預覽

使用 #Preview 巨集搭配內聯模擬資料以快速迭代:

#Preview("空狀態") {
    ItemListView(viewModel: ItemListViewModel(repository: EmptyMockRepository()))
}

#Preview("已載入") {
    ItemListView(viewModel: ItemListViewModel(repository: PopulatedMockRepository()))
}

應避免的反模式

  • 在新程式碼中使用 ObservableObject / @Published / @StateObject / @EnvironmentObject — 請遷移至 @Observable
  • 將非同步工作直接放在 body 或 init 中 — 請使用 .task {} 或明確的載入方法
  • 在不擁有資料的子視圖內將 view model 建立為 @State — 應從父視圖傳入
  • 使用 AnyView 型別抹消 — 對於條件式視圖,請優先使用 @ViewBuilder 或 Group
  • 在與 actor 之間傳遞資料時忽略 Sendable 要求

參考資料

請參閱技能:swift-actor-persistence 以獲得基於 actor 的持久化模式。 請參閱技能:swift-protocol-di-testing 以獲得基於協定的依賴注入與使用 Swift Testing 進行測試。

Individual skills in this repo

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

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

相關技能