Communitygithub.com

swiftui-패턴

SwiftUI 아키텍처 패턴, @Observable을 통한 상태 관리, 뷰 구성, 네비게이션, 성능 최적화 및 최신 iOS/macOS UI 모범 사례. SwiftUI 뷰, @Observable 상태, 네비게이션 또는 렌더링 성능을 빌드하거나 검토할 때 사용하세요.

swiftui-패턴란 무엇인가요?

이 스킬은 Apple 플랫폼에서 선언적이고 성능이 우수한 사용자 인터페이스를 구축하기 위한 최신 SwiftUI 패턴을 제공합니다. 주요 초점은 Observation 프레임워크, 뷰 구성, 타입 안전 네비게이션 및 성능 최적화에 있습니다. 상태 관리를 위해 `@Observable` 매크로 사용을 강조하며, `ObservableObject`와 같은 구식 패턴을 대체하여 속성 수준 변경을 추적하고 불필요한 재렌더링을 방지합니다. 이 스킬은 `NavigationStack`을 통한 타입 안전 라우팅, ViewModifier를 사용한 재사용 가능한 스타일링, `LazyVStack`을 사용한 대규모 컬렉션 최적화, 뷰 업데이트 최소화를 위한 `Equatable` 준수와 같은 기법을 다룹니다. 또한 `AnyView` 사용 방지, 뷰 본문에서의 비동기 작업 방지 등 일반적인 안티패턴을 강조합니다. 이 스킬은 Claude Code, Cursor, Codex와 같은 AI 코딩 에이전트가 SwiftUI 프로젝트를 검토하거나 새로운 SwiftUI 코드를 생성할 때 SwiftUI에 대한 전문가 수준의 조언이 필요할 때 활성화되어야 합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/swiftui-patterns

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

SwiftUI 패턴

Apple 플랫폼에서 선언적이고 성능이 우수한 사용자 인터페이스를 구축하기 위한 최신 SwiftUI 패턴입니다. Observation 프레임워크, 뷰 구성, 타입 안전 네비게이션 및 성능 최적화를 다룹니다.

활성화 시점

  • SwiftUI 뷰를 빌드하고 상태(@State, @Observable, @Binding)를 관리할 때
  • NavigationStack으로 네비게이션 흐름을 설계할 때
  • 뷰 모델과 데이터 흐름을 구조화할 때
  • 목록 및 복잡한 레이아웃의 렌더링 성능을 최적화할 때
  • SwiftUI에서 환경 값과 의존성 주입을 사용할 때

상태 관리

프로퍼티 래퍼 선택

상황에 가장 적합한 가장 간단한 래퍼를 선택하세요:

래퍼사용 사례
@State뷰 지역 값 유형 (토글, 폼 필드, 시트 표시)
@Binding부모의 @State에 대한 양방향 참조
@Observable 클래스 + @State여러 프로퍼티를 가진 소유 모델
@Observable 클래스 (래퍼 없음)부모로부터 전달된 읽기 전용 참조
@Bindable@Observable 프로퍼티에 대한 양방향 바인딩
@Environment.environment()를 통해 주입된 공유 의존성

@Observable ViewModel

ObservableObject 대신 @Observable을 사용하세요. 속성 수준 변경을 추적하여 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() }
    }
}

환경 주입

@EnvironmentObject를 @Environment로 대체하세요:

// 주입
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 {} 또는 명시적 로드 메서드를 사용하세요
  • 데이터를 소유하지 않는 자식 뷰 내에서 @State로 뷰 모델 생성 — 대신 부모로부터 전달하세요
  • 조건부 뷰를 위해 AnyView 유형 지우기 사용 — @ViewBuilder 또는 Group을 선호하세요
  • 액터로/부터 데이터를 전달할 때 Sendable 요구 사항 무시

참고

액터 기반 지속성 패턴은 swift-actor-persistence 기술을 참조하세요. 프로토콜 기반 DI 및 Swift Testing을 사용한 테스트는 swift-protocol-di-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.

관련 스킬