본문으로 건너뛰기
cccskills
무료GitHub에 공개

SwiftUI Patterns

Modern SwiftUI patterns for iOS 18+, including @Observable, navigation, state management, and view composition following SOLID principles

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(2)

  • SKILL.md9.6 KB
  • references/observable-migration.md5.0 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

SwiftUI Patterns Skill

Master modern SwiftUI development with Swift 6 features, @Observable macro, NavigationStack, and architectural patterns that follow SOLID principles.

State Management (iOS 18+ / Swift 6)

@Observable Macro (Preferred over ObservableObject)

The @Observable macro is the modern way to create observable state in SwiftUI:

import SwiftUI

@Observable
final class UserViewModel {
    var user: User?
    var isLoading = false
    var errorMessage: String?

    private let repository: UserRepositoryProtocol

    init(repository: UserRepositoryProtocol) {
        self.repository = repository
    }

    @MainActor
    func loadUser(id: String) async {
        isLoading = true
        defer { isLoading = false }

        do {
            user = try await repository.fetch(id: id)
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}

State Property Wrappers

WrapperUse CaseScope
@StateView-local primitive stateSingle view
@BindingTwo-way connection to parent stateParent-child
@BindableTwo-way binding to @Observable propertyWith @Observable
@EnvironmentDependency injectionEnvironment chain
@ObservableShared mutable state (replaces @ObservableObject)Across views

Using @Bindable with @Observable

@Observable
final class FormViewModel {
    var email = ""
    var password = ""
    var isValid: Bool {
        !email.isEmpty && password.count >= 8
    }
}

struct LoginForm: View {
    @Bindable var viewModel: FormViewModel

    var body: some View {
        Form {
            TextField("Email", text: $viewModel.email)
            SecureField("Password", text: $viewModel.password)
            Button("Login") { /* ... */ }
                .disabled(!viewModel.isValid)
        }
    }
}

Navigation (NavigationStack)

Type-Safe Navigation with Enums

enum AppRoute: Hashable {
    case userProfile(User.ID)
    case settings
    case orderDetail(Order)
    case checkout(Cart)
}

struct ContentView: View {
    @State private var path = NavigationPath()

    var body: some View {
        NavigationStack(path: $path) {
            HomeView(path: $path)
                .navigationDestination(for: AppRoute.self) { route in
                    destinationView(for: route)
                }
        }
    }

    @ViewBuilder
    private func destinationView(for route: AppRoute) -> some View {
        switch route {
        case .userProfile(let userId):
            UserProfileView(userId: userId)
        case .settings:
            SettingsView()
        case .orderDetail(let order):
            OrderDetailView(order: order)
        case .checkout(let cart):
            CheckoutView(cart: cart)
        }
    }
}

Programmatic Navigation

struct ProductListView: View {
    @Binding var path: NavigationPath
    let products: [Product]

    var body: some View {
        List(products) { product in
            Button {
                path.append(AppRoute.productDetail(product.id))
            } label: {
                ProductRow(product: product)
            }
        }
    }

    func navigateToCheckout(cart: Cart) {
        path.append(AppRoute.checkout(cart))
    }

    func popToRoot() {
        path.removeLast(path.count)
    }
}

View Composition

Extract Subviews (Single Responsibility)

// BAD: Monolithic view
struct OrderView: View {
    let order: Order

    var body: some View {
        VStack {
            // 100+ lines of UI code
        }
    }
}

// GOOD: Composed from smaller views
struct OrderView: View {
    let order: Order

    var body: some View {
        ScrollView {
            VStack(spacing: 16) {
                OrderHeaderView(order: order)
                OrderItemsSection(items: order.items)
                OrderSummaryView(
                    subtotal: order.subtotal,
                    tax: order.tax,
                    total: order.total
                )
                OrderActionsView(order: order)
            }
            .padding()
        }
    }
}

Reusable Components with ViewBuilder

struct Card<Content: View>: View {
    let title: String?
    @ViewBuilder let content: () -> Content

    init(title: String? = nil, @ViewBuilder content: @escaping () -> Content) {
        self.title = title
        self.content = content
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            if let title {
                Text(title)
                    .font(.headline)
            }
            content()
        }
        .padding()
        .background(.regularMaterial)
        .clipShape(RoundedRectangle(cornerRadius: 12))
    }
}

// Usage
Card(title: "Order Summary") {
    LabeledContent("Subtotal", value: order.subtotal.formatted(.currency(code: "USD")))
    LabeledContent("Tax", value: order.tax.formatted(.currency(code: "USD")))
    Divider()
    LabeledContent("Total", value: order.total.formatted(.currency(code: "USD")))
        .bold()
}

ViewModifiers for Reusable Styling

struct CardModifier: ViewModifier {
    let cornerRadius: CGFloat

    func body(content: Content) -> some View {
        content
            .padding()
            .background(.regularMaterial)
            .clipShape(RoundedRectangle(cornerRadius: cornerRadius))
            .shadow(radius: 2)
    }
}

extension View {
    func cardStyle(cornerRadius: CGFloat = 12) -> some View {
        modifier(CardModifier(cornerRadius: cornerRadius))
    }
}

// Usage
Text("Hello")
    .cardStyle()

SOLID Principles in SwiftUI

Single Responsibility Principle

Each view should have one reason to change:

// View: Only presentation
struct UserListView: View {
    @State private var viewModel: UserListViewModel

    var body: some View {
        List(viewModel.users) { user in
            UserRow(user: user)
        }
        .task { await viewModel.loadUsers() }
    }
}

// ViewModel: Business logic and state
@Observable @MainActor
final class UserListViewModel {
    private let service: UserServiceProtocol
    var users: [User] = []

    init(service: UserServiceProtocol) {
        self.service = service
    }

    func loadUsers() async {
        users = (try? await service.fetchAll()) ?? []
    }
}

Open/Closed Principle

Extend behavior without modifying existing code:

// Base button style
struct PrimaryButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding()
            .background(Color.accentColor)
            .foregroundStyle(.white)
            .clipShape(RoundedRectangle(cornerRadius: 8))
            .opacity(configuration.isPressed ? 0.8 : 1)
    }
}

// Extended without modifying original
struct LoadingButtonStyle: ButtonStyle {
    let isLoading: Bool

    func makeBody(configuration: Configuration) -> some View {
        HStack {
            if isLoading {
                ProgressView()
                    .tint(.white)
            }
            configuration.label
        }
        .padding()
        .background(Color.accentColor)
        .foregroundStyle(.white)
        .clipShape(RoundedRectangle(cornerRadius: 8))
        .opacity(configuration.isPressed || isLoading ? 0.8 : 1)
    }
}

Dependency Inversion Principle

Depend on abstractions via Environment:

// Protocol abstraction
protocol AnalyticsProtocol {
    func track(event: String, properties: [String: Any])
}

// Environment key
private struct AnalyticsKey: EnvironmentKey {
    static let defaultValue: AnalyticsProtocol = NoOpAnalytics()
}

extension EnvironmentValues {
    var analytics: AnalyticsProtocol {
        get { self[AnalyticsKey.self] }
        set { self[AnalyticsKey.self] = newValue }
    }
}

// Usage in view
struct ProductView: View {
    @Environment(\.analytics) private var analytics
    let product: Product

    var body: some View {
        Button("Buy") {
            analytics.track(event: "purchase", properties: ["product_id": product.id])
        }
    }
}

// Inject real or mock
ProductView(product: product)
    .environment(\.analytics, FirebaseAnalytics()) // Production
    .environment(\.analytics, MockAnalytics())     // Testing

Performance Optimization

Avoid Expensive Body Computations

// BAD: Expensive computation in body
var body: some View {
    let sortedItems = items.sorted { $0.date > $1.date } // Called on every render
    List(sortedItems) { item in
        ItemRow(item: item)
    }
}

// GOOD: Computed outside body or cached
@Observable
final class ItemListViewModel {
    var items: [Item] = []

    var sortedItems: [Item] {
        items.sorted { $0.date > $1.date }
    }
}

Use @Previewable for Previews (iOS 18+)

#Preview {
    @Previewable @State var count = 0

    VStack {
        Text("Count: \(count)")
        Button("+1") { count += 1 }
    }
}

Lazy Loading

LazyVStack {
    ForEach(items) { item in
        ItemRow(item: item)
    }
}

LazyVGrid(columns: [GridItem(.adaptive(minimum: 150))]) {
    ForEach(products) { product in
        ProductCard(product: product)
    }
}

References

  • See references/observable-migration.md for ObservableObject to @Observable migration guide
  • See references/navigation-patterns.md for advanced navigation patterns
  • See references/mvvm-architecture.md for complete MVVM implementation

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

When the user wants to A/B test App Store product page elements to improve conversion rate. Also use when the user mentions "A/B test", "product page optimization", "test my screenshots", "test my icon", "conversion rate optimization", "CPP", or "custom product pages". For screenshot design, see screenshot-optimization. For metadata optimization, see metadata-optimization.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

JordanCoin/ios-skills-collection62026년 9월 10일 업데이트

Discover and configure Bluetooth and Wi-Fi accessories using AccessorySetupKit. Use when presenting a privacy-preserving accessory picker, defining discovery descriptors for BLE or Wi-Fi devices, handling accessory session events, migrating from CoreBluetooth permission-based scanning, or setting up accessories without requiring broad Bluetooth permissions.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

JordanCoin/ios-skills-collection62026년 9월 10일 업데이트

Implement, review, or improve Live Activities and Dynamic Island experiences in iOS apps using ActivityKit. Use when building real-time updating widgets for the Lock Screen and Dynamic Island — delivery tracking, sports scores, ride-sharing status, workout timers, media playback, or any time-sensitive information that updates in real time. Also use when working with ActivityKit, ActivityAttributes, Activity lifecycle (request/update/end), Dynamic Island layouts (compact/minimal/expanded), push-to-update Live Activities, or Lock Screen live widgets.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

JordanCoin/ios-skills-collection62026년 9월 10일 업데이트

Measure ad effectiveness with privacy-preserving attribution using AdAttributionKit. Use when registering ad impressions, handling attribution postbacks, updating conversion values, implementing re-engagement attribution, configuring publisher or advertiser apps, or replacing SKAdNetwork with AdAttributionKit for ad measurement.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

JordanCoin/ios-skills-collection62026년 9월 10일 업데이트

alarmkit

무료

Implement AlarmKit alarms and countdown timers for iOS and iPadOS with Lock Screen, Dynamic Island, and Apple Watch system UI. Covers AlarmManager scheduling, AlarmAttributes and AlarmPresentation, AlarmButton stop and snooze actions, authorization, state observation, and Live Activity integration. Use when building wake-up alarms, countdown timers, or alarm-style alerts that need Apple's system alarm experience.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

JordanCoin/ios-skills-collection62026년 9월 10일 업데이트

When the user wants to optimize their Google Play Store listing — title, short description, full description, keywords, ratings, or Play Store-specific features. Use when the user mentions "Google Play", "Android", "Play Store", "Play Console", "short description", "full description indexed", "Google Play ASO", or wants Google Play-specific keyword, creative, or ratings strategy. For iOS App Store optimization, see aso-audit and metadata-optimization.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

JordanCoin/ios-skills-collection62026년 9월 10일 업데이트

JordanCoin의 스킬 모두 보기

이 스킬의 문제 신고