本文へスキップ
Skillpedia
WebサイトとUI(フロントエンド)280k · #252

swiftui-patterns

できること

このガイドでは、SwiftUIを使ってiPhoneやMac向けのモダンなアプリを作るためのベストプラクティスを紹介します。コードの整理方法、データの管理方法、そして効率よくナビゲーションを機能させる方法を説明します。

使う場面

  • ✓SwiftUIで新しいアプリを作り始めるとき。
  • ✓既存のアプリのコードを整理したいとき。
  • ✓アプリの動作が遅い、または反応が悪いとき。

スキルのリンク

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/swiftui-patterns/SKILL.md

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/affaan-m/ECC/blob/main/pi/core/skills/swiftui-patterns/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“SwiftUIのコードを、データ管理とナビゲーションの面でどのように整理すればよいですか?”

毎週5つの新しいスキル。1分で読めます。

仕組み

`@Observable`によるデータ管理や、`NavigationStack`によるナビゲーションなど、SwiftUIの具体的な機能の使い方を紹介します。コードをすっきりさせ、アプリを速くすることが目的です。

技術的な内容(元のSKILL.md)

作者による元のテキスト(英語)をGitHubからそのまま表示しています。

SwiftUI Patterns

Modern SwiftUI patterns for building declarative, performant user interfaces on Apple platforms. Covers the Observation framework, view composition, type-safe navigation, and performance optimization.

When to Activate

  • Building SwiftUI views and managing state (@State, @Observable, @Binding)
  • Designing navigation flows with NavigationStack
  • Structuring view models and data flow
  • Optimizing rendering performance for lists and complex layouts
  • Working with environment values and dependency injection in SwiftUI

State Management

Property Wrapper Selection

Choose the simplest wrapper that fits:

Wrapper Use Case
@State View-local value types (toggles, form fields, sheet presentation)
@Binding Two-way reference to parent's @State
@Observable class + @State Owned model with multiple properties
@Observable class (no wrapper) Read-only reference passed from parent
@Bindable Two-way binding to an @Observable property
@Environment Shared dependencies injected via .environment()

@Observable ViewModel

Use @Observable (not ObservableObject) — it tracks property-level changes so SwiftUI only re-renders views that read the changed property:

@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()) ?? []
    }
}

View Consuming the 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 Injection

Replace @EnvironmentObject with @Environment:

// Inject
ContentView()
    .environment(authManager)

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

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

View Composition

Extract Subviews to Limit Invalidation

Break views into small, focused structs. When state changes, only the subview reading that state re-renders:

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 for Reusable Styling

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

Navigation

Type-Safe NavigationStack

Use NavigationStack with NavigationPath for programmatic, type-safe routing:

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

Performance

…

よくある質問

`@State`と`@Observable`の違いは何ですか?

`@State`は、1つの画面だけに属するシンプルなデータに使います。`@Observable`は、複数の場所で共有したり、より複雑なデータを管理したりするのに向いています。画面の中で実際に再描画が必要な部分だけを更新できるので、効率的です。

画面遷移をより確実にするにはどうすればよいですか?

`NavigationPath`と組み合わせて`NavigationStack`を使います。どの画面に、どのデータを持って移動できるかを明確に定義でき、よくある画面遷移のエラーを防げます。

アプリの動作が遅いのはなぜですか?

画面の中で不要な部分まで再描画されている可能性があります。大きなリストには`LazyVStack`を使い、画面を小さな部品に分けて、必要な部分だけが更新されるようにしましょう。

詳細

作者による元の説明

SwiftUI architecture patterns, state management with @Observable, view composition, navigation, performance optimization, and modern iOS/macOS UI best practices. Use when building or reviewing SwiftUI views, @Observable state, navigation, or render performance.

repo: affaan-m/ECC

人気

GitHubのスター
280k
ランキング
#252
ライセンス
MIT
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル