Communitygithub.com

swiftui-patterns

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

swiftui-patterns란 무엇인가요?

이 스킬은 Apple 플랫폼에서 선언적이고 성능이 뛰어난 사용자 인터페이스를 구축하기 위한 현대적인 SwiftUI 패턴을 제공합니다. Observation 프레임워크를 사용한 상태 관리, 뷰 구성, 타입 안전 탐색, 렌더링 성능 최적화를 다룹니다. SwiftUI를 사용하는 모든 Apple 플랫폼(iOS, macOS, watchOS, tvOS, visionOS)에서 작동하며, Claude Code, Cursor, Codex와 같은 AI 에이전트에서 SwiftUI 코드를 작성하거나 검토할 때 활성화됩니다. SKILL.md 문서는 @State, @Observable, @Binding, @Environment와 같은 속성 래퍼 선택 가이드, @Observable 기반 ViewModel 패턴, NavigationStack을 활용한 타입 안전 라우팅, Lazy 컨테이너와 Equatable 준수를 통한 성능 최적화, 그리고 ObservableObject 및 AnyView와 같은 안티 패턴을 피하는 방법을 설명합니다. 개발자가 SwiftUI 앱을 구조화하고, 불필요한 재렌더링을 방지하며, 유지보수 가능하고 테스트 가능한 코드를 작성하는 데 도움을 줍니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/everything-claude-code/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 ?? "Guest")
    }
}

뷰 구성

무효화 제한을 위한 하위 뷰 추출

뷰를 작고 집중된 구조체로 나누세요. 상태가 변경되면 해당 상태를 읽는 하위 뷰만 다시 렌더링됩니다:

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

성능

큰 컬렉션에는 Lazy 컨테이너 사용

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 준수

body가 비용이 많이 드는 뷰의 경우, 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로 마이그레이션하세요
  • async 작업을 body 또는 init에 직접 배치 — .task {} 또는 명시적 로드 메서드를 사용하세요
  • 데이터를 소유하지 않은 하위 뷰 내에서 @State로 뷰 모델 생성 — 대신 부모로부터 전달하세요
  • AnyView 타입 지우기 사용 — 조건부 뷰에는 @ViewBuilder 또는 Group을 선호하세요
  • actor에 데이터를 전달할 때 Sendable 요구 사항 무시

참조

auditor 기반 지속성 패턴은 skill: swift-actor-persistence를 참조하세요. 프로토콜 기반 DI 및 Swift Testing을 사용한 테스트는 skill: 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/claude-api

Anthropic Claude API patterns for Python and TypeScript. Covers Messages API, streaming, tool use, vision, extended thinking, batches, prompt caching, and Claude Agent SDK. Use when building applications with the Claude API or Anthropic SDKs.

affaan-m/everything-claude-code

End-to-end marketing campaign planning and execution. Covers audience research, positioning, campaign angle definition, landing page copy, email sequences, social posts, ad copy, short-form video scripts, and content calendars. Use as the orchestration layer for multi-channel product launches. Use when planning or executing a multi-channel product launch, or producing landing page, email, social, or ad copy.

affaan-m/everything-claude-code

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/everything-claude-code-conventions

Development conventions and patterns for everything-claude-code. JavaScript project with conventional commits.

affaan-m/frontend-design

Create distinctive, production-grade frontend interfaces with high design quality. Use when the user asks to build web components, pages, or applications and the visual direction matters as much as the code quality.

affaan-m/gget

gget CLI and Python workflow for quick genomic database queries, sequence lookup, BLAST-style searches, enrichment checks, and reproducible bioinformatics evidence logs.

affaan-m/literature-review

Systematic literature-review workflow for academic, biomedical, technical, and scientific topics, including search planning, source screening, synthesis, citation checks, and evidence logging.

affaan-m/motion-ui

Production-ready UI motion system for React/Next.js. Use when implementing animations, transitions, or motion patterns.

affaan-m/project-guidelines-example

Example project-specific skill template based on a real production application.

affaan-m/pubmed-database

Direct PubMed and NCBI E-utilities search workflows for biomedical literature, MeSH queries, PMID lookup, citation retrieval, and API-backed literature monitoring.

affaan-m/scholar-evaluation

Structured scholarly-work evaluation for papers, proposals, literature reviews, methods sections, evidence quality, citation support, and research-writing feedback.

affaan-m/uspto-database

USPTO patent and trademark data workflow for official record lookup, PatentSearch queries, TSDR checks, assignment data, and reproducible IP research logs.

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.

관련 스킬