Communitygithub.com

ComeOnOliver/skillshub

SwiftUI 아키텍처 패턴, @Observable을 사용한 상태 관리, 뷰 컴포지션, 네비게이션, 성능 최적화 및 최신 iOS/macOS UI 모범 사례

skillshub란 무엇인가요?

이 스킬은 Apple 플랫폼에서 SwiftUI를 사용하여 선언적이고 성능이 뛰어난 사용자 인터페이스를 구축하기 위한 종합적인 가이드입니다. Observation 프레임워크를 중심으로 한 상태 관리, 타입 안전 네비게이션, 뷰 컴포지션, 성능 최적화 방법을 다룹니다. Claude Code, Cursor, Codex 등 AI 어시스턴트에서 이 스킬을 활성화하면 SwiftUI 개발 시 최신 패턴과 모범 사례를 따를 수 있도록 도와줍니다. 이 스킬은 특히 @Observable을 활용한 ViewModel 패턴, NavigationStack을 이용한 타입 안전 라우팅, Lazy 컨테이너와 Equatable 준수를 통한 렌더링 성능 최적화에 중점을 둡니다. 또한 ObservableObject와 같은 레거시 패턴 대신 @Observable을 사용하도록 권장하는 등 최신 SwiftUI 트렌드를 반영하고 있습니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/ComeOnOliver/skillshub/tree/HEAD/skills/affaan-m/everything-claude-code/swiftui-patterns

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

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

문서

SwiftUI Patterns

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

활성화 시점

  • SwiftUI 뷰 및 상태 관리(@State, @Observable, @Binding) 구축
  • NavigationStack을 사용한 네비게이션 플로우 설계
  • 뷰 모델 및 데이터 플로우 구조화
  • 리스트 및 복잡한 레이아웃의 렌더링 성능 최적화
  • 환경 값 및 의존성 주입 작업

상태 관리

프로퍼티 래퍼 선택

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

래퍼사용 사례
@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 준수

바디가 비싼 뷰의 경우 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("Empty state") {
    ItemListView(viewModel: ItemListViewModel(repository: EmptyMockRepository()))
}

#Preview("Loaded") {
    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.

ComeOnOliver/skillshub

Create stunning, animation-rich HTML presentations from scratch or by converting PowerPoint files. Use when the user wants to build a presentation, convert a PPT/PPTX to web, or create slides for a talk/pitch. Helps non-designers discover their aesthetic through visual exploration rather than abstract choices.

ComeOnOliver/skillshub

Next.js 16+ 和 Turbopack — 增量打包、文件系统缓存、开发速度,以及何时使用 Turbopack 与 webpack。

ComeOnOliver/skillshub

See, Understand, Act on video and audio. See- ingest from local files, URLs, RTSP/live feeds, or live record desktop; return realtime context and playable stream links. Understand- extract frames, build visual/semantic/temporal indexes, and search moments with timestamps and auto-clips. Act- transcode and normalize (codec, fps, resolution, aspect ratio), perform timeline edits (subtitles, text/image overlays, branding, audio overlays, dubbing, translation), generate media assets (image, audio, video), and create real time alerts for events from live streams or desktop capture.

ComeOnOliver/skillshub

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.

ComeOnOliver/skillshub

Next.js 15 애플리케이션을 위한 프론트엔드 개발 가이드라인. React 19, TypeScript, Shadcn/ui, Tailwind CSS를 사용한 모던 패턴. Server Components, Client Components, App Router, 파일 구조, Shadcn/ui 컴포넌트, 성능 최적화, TypeScript 모범 사례 포함. 컴포넌트, 페이지, 기능 생성, 데이터 페칭, 스타일링, 라우팅, 프론트엔드 코드 작업 시 사용.

ComeOnOliver/skillshub

Provides Tamagui patterns for config v4, compiler optimization, styled context, and cross-platform styling. Must use when working with Tamagui projects (tamagui.config.ts, @tamagui imports).

ComeOnOliver/skillshub

Create distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.

ComeOnOliver/skillshub

Create high-converting, visually distinctive landing pages. Use when building marketing pages, product launches, SaaS homepages, or any single-page conversion-focused website. Guides section-by-section composition with anti-AI-slop principles.

ComeOnOliver/skillshub

Auto-loaded context for Portfolio Buddy 2 development. Use for ANY task involving: React 19 development, TypeScript, portfolio analysis features, metrics calculations, trading strategy comparison, or working with the Portfolio Buddy 2 codebase. Contains tech stack, known issues, and architectural constraints.

ComeOnOliver/skillshub

Next.js development tooling via MCP. Inspect routes, components, build info, and debug Next.js apps. Use when working on Next.js applications, debugging routing, or inspecting app structure. NOT for general React or non-Next.js projects.

ComeOnOliver/skillshub

Implement UI using Shadcn MCP (atoms/theme) and 21st.dev MCP (complex sections). Use when adding buttons, layouts, or generating landing pages.

ComeOnOliver/skillshub

A conceptual skill for building an API client in Next.js that handles JWT tokens

ComeOnOliver/skillshub

Best practices and patterns for Next.js App Router, Server Actions, and Routing in this project.

ComeOnOliver/skillshub

The Design System, Theme, and UX rules for the Physical AI Hub.

ComeOnOliver/skillshub

Comprehensive frontend development skill for building modern, performant web applications using ReactJS, NextJS, TypeScript, Tailwind CSS. Includes component scaffolding, performance optimization, bundle analysis, and UI best practices. Use when developing frontend features, optimizing performance, implementing UI/UX designs, managing state, or reviewing frontend code.

ComeOnOliver/skillshub

This document captures learnings from fixing keyboard navigation issues when floating components (Select, DropdownMenu, Popover) have CSS open/close animations.

ComeOnOliver/skillshub

Build Next.js 16 applications with correct patterns and distinctive design. Use when creating pages, layouts, dynamic routes, upgrading from Next.js 15, or implementing proxy.ts. Covers breaking changes (async params/searchParams, Turbopack, cacheComponents) and frontend aesthetics. NOT when building non-React or backend-only applications.

ComeOnOliver/skillshub

Comprehensive Framer Motion animation library for React. Covers motion components, variants, gestures, page transitions, and scroll animations. Use when adding animations to React/Next.js applications.

ComeOnOliver/skillshub

Next.js 16+ uses App Router with Server Components by default. Client Components are only used when interactivity is needed (hooks, event handlers, browser APIs).

ComeOnOliver/skillshub

Build interfaces that resonate, not just render. This skill enforces bold, intentional

관련 스킬