
Swiftui Patterns
- 5.8k installs
- 238k repo stars
- Updated August 5, 2026
- affaan-m/everything-claude-code
swiftui-patterns is an agent skill documenting @Observable state management, view composition, NavigationStack routing, performance tuning, and anti-patterns for modern iOS and macOS SwiftUI.
About
This skill documents modern SwiftUI architecture patterns for Apple platforms using the Observation framework, view composition, type-safe navigation, and performance tuning. Activation covers building views with @State, @Observable, and @Binding, designing NavigationStack flows, structuring view models and data flow, optimizing list rendering, and injecting dependencies via environment values. State management maps each property wrapper to its role, favoring @Observable over ObservableObject for property-level invalidation and @Environment over @EnvironmentObject for shared services. View composition splits screens into focused subviews and reusable ViewModifier styles to limit rerenders. NavigationStack with NavigationPath and a hashable Destination enum enables programmatic type-safe routing through an @Observable Router. Performance guidance uses LazyVStack, stable ForEach identifiers, .task for async work, Equatable views for expensive bodies, and #Preview macros with mock repositories. Documented anti-patterns reject legacy ObservableObject wrappers, async in body or init, child-owned view models, AnyView erasure, and ignored Sendable rules with actor data.
- Map @State, @Binding, @Observable, @Bindable, and @Environment to the simplest correct ownership model
- Split views into focused subviews and ViewModifier styles so only readers of changed state rerender
- Route with NavigationStack, NavigationPath, and hashable Destination cases via an @Observable Router
- Use LazyVStack, stable ForEach IDs, .task async loading, and Equatable bodies for scroll performance
- Reject ObservableObject, @EnvironmentObject, AnyView, and async work inside body or init
Swiftui Patterns by the numbers
- 5,792 all-time installs (skills.sh)
- +230 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #28 of 1,039 Mobile Development skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
swiftui-patterns capabilities & compatibility
- Capabilities
- map @state, @binding, @observable, @bindable, an · split views into focused subviews and viewmodifi · route with navigationstack, navigationpath, and · use lazyvstack, stable foreach ids, .task async · reject observableobject, @environmentobject, any
- Use cases
- frontend · ui design
What swiftui-patterns says it does
`ObservableObject` ではなく `@Observable` を使用する——プロパティレベルの変更を追跡するため、SwiftUIは変更されたプロパティを読み取ったビューのみを再レンダリングする
新しいコードで `ObservableObject` / `@Published` / `@StateObject` / `@EnvironmentObject` を使用する——`@Observable` に移行する
npx skills add https://github.com/affaan-m/everything-claude-code --skill swiftui-patternsAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 5.8k |
|---|---|
| repo stars | ★ 238k |
| Security audit | 3 / 3 scanners passed |
| Last updated | August 5, 2026 |
| Repository | affaan-m/everything-claude-code ↗ |
What it does
Implement @Observable state, NavigationStack routing, view composition, and performance patterns for modern SwiftUI on Apple platforms.
Who is it for?
iOS or macOS developers building SwiftUI views with Observation, NavigationStack, environment injection, and scroll-heavy layouts.
Skip if: UIKit-only screens, actor persistence deep dives, or protocol DI testing covered by companion swift-actor-persistence and swift-protocol-di-testing skills.
When should I use this skill?
Activate when building SwiftUI views and state, designing NavigationStack flows, structuring view models, optimizing list rendering, or using environment dependency injection.
What you get
Agents apply documented wrapper selection, subview extraction, type-safe routers, lazy containers, and preview mocks for maintainable high-performance SwiftUI features.
- swiftui view patterns
- navigation flows
- performance optimizations
Files
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 を使用する:
// Inject
ContentView()
.environment(authManager)
// Consume
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)
}
}パフォーマンス
大規模なコレクションにレイジーコンテナを使用する
LazyVStack と LazyHStack はビューが表示される時のみ作成する:
ScrollView {
LazyVStack(spacing: 8) {
ForEach(items) { item in
ItemRow(item: item)
}
}
}安定した識別子
ForEach では常に安定した一意のIDを使用する——配列インデックスは避ける:
// Use Identifiable conformance or explicit 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 must conform to Equatable
static func == (lhs: Self, rhs: Self) -> Bool {
lhs.dataPoints == rhs.dataPoints
}
var body: some View {
// Complex chart rendering
}
}プレビュー
インラインのモックデータで #Preview マクロを使用して素早い反復を行う:
#Preview("Empty state") {
ItemListView(viewModel: ItemListViewModel(repository: EmptyMockRepository()))
}
#Preview("Loaded") {
ItemListView(viewModel: ItemListViewModel(repository: PopulatedMockRepository()))
}避けるべきアンチパターン
- 新しいコードで
ObservableObject/@Published/@StateObject/@EnvironmentObjectを使用する——@Observableに移行する bodyやinit内に直接非同期処理を置く——.task {}または明示的なロードメソッドを使用する- データを所有しないサブビューでViewModelを
@Stateとして作成する——代わりに親ビューから渡す AnyViewによる型消去を使用する——条件付きビューには@ViewBuilderまたはGroupを優先する- ActorとのデータのやりとりにおいてSendable要件を無視する
参照
Actorベースの永続化パターンについては、スキル swift-actor-persistence を参照。 プロトコルベースのDIとSwift Testingを使用したテストについては、スキル swift-protocol-di-testing を参照。
Related skills
Forks & variants (1)
Swiftui Patterns has 1 known copy in the catalog totaling 1.4k installs. They canonicalize to this original listing.
- affaan-m - 1.4k installs
FAQ
When should I choose @Observable over ObservableObject?
Use @Observable so SwiftUI tracks property-level changes and rerenders only views that read the mutated properties, instead of broadcasting object-wide updates.
How should async loading run in SwiftUI views?
Use .task for async work so loads start with the view and cancel automatically when the view disappears; never place I/O or network calls directly in body or init.
What navigation pattern does the skill recommend?
Use NavigationStack with NavigationPath and a hashable Destination enum, managed by an @Observable Router injected through the environment for type-safe programmatic routing.
Is Swiftui Patterns safe to install?
skills.sh reports 3 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.