swiftui-patterns
dpearson2699/swift-ios-skills
Build and review SwiftUI views with modern MV architecture, state management, and composition patterns.
What is swiftui-patterns?
Provides guidance on structuring SwiftUI apps using the Model-View pattern, @Observable ownership rules, state management with @State/@Bindable/@Environment, view composition, async data loading, and iOS 17+ patterns. Use when architecting SwiftUI app state, managing observable objects, composing view hierarchies, or reviewing SwiftUI code for pattern correctness.
- Teaches MV (Model-View) architecture with lightweight views and service injection
- Covers @Observable ownership rules and @State/@Bindable/@Environment wiring
- Guides view decomposition, computed properties, and custom ViewModifiers
- Explains environment value setup and granular change tracking
- Demonstrates async data loading with .task and .refreshable
- Provides iOS 26+ API guidance, Writing Tools integration, and performance guidelines
How to install swiftui-patterns
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill swiftui-patternsHow to use swiftui-patterns
- 1.Review the MV pattern section to understand when to use models vs. view models
- 2.Study the @Observable ownership table to decide which wrapper (@State, @Bindable, @Environment) fits your use case
- 3.Extract subviews using computed properties or standalone View structs to keep views focused
- 4.Set up @Observable models with @MainActor isolation for UI-bound state
- 5.Use .task and .onChange for orchestration instead of view model logic
- 6.Apply the view ordering convention (environment, properties, state, computed vars, body, helpers)
- 7.Reference the review checklist when auditing SwiftUI code
Use cases
- Structuring app state and deciding between @State, @Bindable, and @Environment
- Refactoring views to follow MV pattern instead of introducing unnecessary view models
- Composing large views into focused, reusable subviews
- Setting up @Observable models with proper @MainActor isolation
- Loading async data and handling loading/error/loaded states
- iOS/SwiftUI developers building new apps or refactoring existing ones
- Teams adopting modern SwiftUI patterns (iOS 17+)
- Developers migrating from ObservableObject to @Observable
- Code reviewers ensuring consistent architecture and state management
swiftui-patterns FAQ
Use @State when the view owns and creates the @Observable object. Use @Bindable when the view receives an @Observable object and needs two-way bindings ($property). Use @Environment when accessing a shared @Observable object injected into the environment.
No. Default to the MV pattern: keep views lightweight and inject services/models via @Environment. Only introduce a view model if the existing codebase already uses them. Split large views into smaller subviews instead.
Use .task { await loadData() } on the view. Store the result in @State and switch on a ViewState enum (loading, error, loaded). Use .refreshable { await loadData() } to enable pull-to-refresh.
UI-bound @Observable stores should be isolated to @MainActor to ensure thread-safe mutations when SwiftUI views own or bind to them. Observation tracks changes but does not make shared mutable state thread-safe.
SwiftUI only re-renders views that read properties that actually changed. If a view reads 'items' but not 'isLoading', changing 'isLoading' does not trigger a re-render, unlike ObservableObject which re-renders on any change.
Full instructions (SKILL.md)
Source of truth, from dpearson2699/swift-ios-skills.
name: swiftui-patterns description: "Builds and reviews SwiftUI views with modern MV architecture, state management, view composition, and migration/availability guidance. Covers @Observable ownership rules, @State/@Bindable/@Environment wiring, view decomposition, custom ViewModifiers, environment values, async data loading with .task, iOS 26+ handoff reminders, Writing Tools, clipboard availability caveats, and performance guidelines. Use when structuring SwiftUI app state, managing @Observable, composing view hierarchies, or correcting SwiftUI pattern guidance."
SwiftUI Patterns
Modern SwiftUI patterns targeting iOS 26+ with Swift 6.3. Covers architecture, state management, view composition, environment wiring, async loading, design polish, and platform/share integration. Navigation, layout, animation, and Liquid Glass patterns live in dedicated sibling skills. Patterns are backward-compatible to iOS 17 unless noted.
Contents
- Architecture: Model-View (MV) Pattern
- State Management
- View Ordering Convention
- View Composition
- Environment
- Async Data Loading
- iOS 26+ New APIs
- Performance Guidelines
- HIG Alignment
- Writing Tools (iOS 18+)
- Common Mistakes
- Review Checklist
- References
Scope boundary: This skill covers architecture, state ownership, composition, environment wiring, async loading, and related SwiftUI app structure patterns. Detailed navigation patterns are covered in the swiftui-navigation skill, including NavigationStack, NavigationSplitView, sheets, tabs, and deep-linking patterns. Detailed layout, container, and component patterns are covered in the swiftui-layout-components skill, including stacks, grids, lists, scroll view patterns, forms, controls, search UI with .searchable, overlays, and related layout components. Detailed animation choreography is covered in swiftui-animation. Liquid Glass adoption, custom glass controls, scroll edge effects, .scrollEdgeEffectStyle, and .backgroundExtensionEffect are covered in swiftui-liquid-glass.
Architecture: Model-View (MV) Pattern
Default to MV -- views are lightweight state expressions; models and services own business logic. Do not introduce view models unless the existing code already uses them.
Core principles:
- Favor
@State,@Environment,@Query,.task, and.onChangefor orchestration - Inject services and shared models via
@Environment; keep views small and composable - Split large views into smaller subviews rather than introducing a view model
- Test models, services, and business logic; keep views simple and declarative
struct FeedView: View {
@Environment(FeedClient.self) private var client
enum ViewState {
case loading, error(String), loaded([Post])
}
@State private var viewState: ViewState = .loading
var body: some View {
List {
switch viewState {
case .loading:
ProgressView()
case .error(let message):
ContentUnavailableView("Error", systemImage: "exclamationmark.triangle",
description: Text(message))
case .loaded(let posts):
ForEach(posts) { post in
PostRow(post: post)
}
}
}
.task { await loadFeed() }
.refreshable { await loadFeed() }
}
private func loadFeed() async {
do {
let posts = try await client.getFeed()
viewState = .loaded(posts)
} catch {
viewState = .error(error.localizedDescription)
}
}
}
For MV pattern rationale, app wiring, and lightweight client examples, see references/architecture-patterns.md.
State Management
@Observable Ownership Rules
Important: Isolate UI-bound @Observable stores and view models on @MainActor when SwiftUI views own them, mutate them, or bind to their properties. Observation tracks changes; it does not make shared mutable state thread-safe. Domain models that do not touch UI state can use their own isolation strategy.
| Wrapper | When to Use |
|---|---|
@State | View owns the object or value. Creates and manages lifecycle. |
let | View receives an @Observable object. Read-only observation -- no wrapper needed. |
@Bindable | View receives an @Observable object and needs two-way bindings ($property). |
@Environment(Type.self) | Access shared @Observable object from environment. |
@State (value types) | View-local simple state: toggles, counters, text field values. Always private. |
@Binding | Two-way connection to parent's @State or @Bindable property. |
Ownership Pattern
// UI-bound @Observable store -- main-actor isolated
@MainActor
@Observable final class ItemStore {
var title = ""
var items: [Item] = []
}
// View that OWNS the model
struct ParentView: View {
@State private var viewModel = ItemStore()
var body: some View {
ChildView(store: viewModel)
.environment(viewModel)
}
}
// View that READS (no wrapper needed for @Observable)
struct ChildView: View {
let store: ItemStore
var body: some View { Text(store.title) }
}
// View that BINDS (needs two-way access)
struct EditView: View {
@Bindable var store: ItemStore
var body: some View {
TextField("Title", text: $store.title)
}
}
// View that reads from ENVIRONMENT
struct DeepView: View {
@Environment(ItemStore.self) private var store
var body: some View {
@Bindable var s = store
TextField("Title", text: $s.title)
}
}
Granular tracking: SwiftUI only re-renders views that read properties that changed. If a view reads items but not isLoading, changing isLoading does not trigger a re-render. This is a major performance advantage over ObservableObject.
Legacy ObservableObject
Only use if supporting iOS 16 or earlier. @StateObject → @State, @ObservedObject → let, @EnvironmentObject → @Environment(Type.self).
View Ordering Convention
Order members top to bottom: 1) @Environment 2) let properties 3) @State / stored properties 4) computed var 5) init 6) body 7) view builders / helpers 8) async functions
View Composition
Extract Subviews
Break views into focused subviews. Each should have a single responsibility.
var body: some View {
VStack {
HeaderSection(title: title, isPinned: isPinned)
DetailsSection(details: details)
ActionsSection(onSave: onSave, onCancel: onCancel)
}
}
Computed View Properties
Keep related subviews as computed properties in the same file; extract to a standalone View struct when reuse is intended or the subview carries its own state.
var body: some View {
List {
header
filters
results
}
}
private var header: some View {
VStack(alignment: .leading) {
Text(title).font(.title2)
Text(subtitle).font(.subheadline)
}
}
ViewBuilder Functions
For conditional logic that does not warrant a separate struct:
@ViewBuilder
private func statusBadge(for status: Status) -> some View {
switch status {
case .active: Text("Active").foregroundStyle(.green)
case .inactive: Text("Inactive").foregroundStyle(.secondary)
}
}
Custom View Modifiers
Extract repeated styling into ViewModifier:
struct CardStyle: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(.background)
.clipShape(.rect(cornerRadius: 12))
.shadow(radius: 2)
}
}
extension View { func cardStyle() -> some View { modifier(CardStyle()) } }
Stable View Tree
Avoid top-level conditional view swapping. Prefer a single stable base view with conditions inside sections or modifiers. When a view file exceeds ~300 lines, split with extensions and // MARK: - comments.
Environment
Custom Environment Values
Use @Entry for custom environment values and actions. It generates the entry boilerplate for EnvironmentValues.
extension EnvironmentValues {
@Entry var theme: Theme = .default
@Entry var refreshFeed: @Sendable () async -> Void = {}
}
// Usage
.environment(\.theme, customTheme)
.environment(\.refreshFeed) { await feedStore.refresh() }
@Environment(\.theme) private var theme
@Environment(\.refreshFeed) private var refreshFeed
For iOS 17-compatible code or older compatibility shims, use manual EnvironmentKey types instead.
Common Built-in Environment Values
@Environment(\.dismiss) var dismiss
@Environment(\.colorScheme) var colorScheme
@Environment(\.dynamicTypeSize) var dynamicTypeSize
@Environment(\.horizontalSizeClass) var sizeClass
@Environment(\.isSearching) var isSearching
@Environment(\.openURL) var openURL
@Environment(\.modelContext) var modelContext
Async Data Loading
Always use .task -- it cancels automatically on view disappear:
struct ItemListView: View {
@State var store = ItemStore()
var body: some View {
List(store.items) { item in
ItemRow(item: item)
}
.task { await store.load() }
.refreshable { await store.refresh() }
}
}
Use .task(id:) to re-run when a dependency changes:
.task(id: searchText) {
guard !searchText.isEmpty else { return }
await search(query: searchText)
}
Never create manual Task in onAppear unless you need to store a reference for cancellation. Exception: Task {} is acceptable in synchronous action closures (e.g., Button actions) for immediate state updates before async work.
iOS 26+ New APIs
.scrollEdgeEffectStyle(.soft, for: .top)-- fading edge effect on scroll edges.backgroundExtensionEffect()-- mirror/blur at safe area edges@Animatablemacro -- synthesizesAnimatableDataconformance automatically (seeswiftui-animationskill)TextEditor(text: Binding<AttributedString>)-- rich text editing with attributed strings
Keep these as routing reminders in this skill. For Liquid Glass visual treatment, scroll edge effects, glass controls, and availability gating, use swiftui-liquid-glass; for detailed animation APIs, use swiftui-animation.
Clipboard command modifiers are not iOS 26 defaults: .copyable, .cuttable, and command-based .pasteDestination(for:action:validator:) are macOS 13+ and iOS/iPadOS/Mac Catalyst 27 beta in current Apple docs. For iOS 26 targets, use UIPasteboard for custom clipboard commands, or use drag/drop and ShareLink for Transferable flows. See references/platform-and-sharing.md.
Performance Guidelines
- Lazy stacks/grids: Use
LazyVStack,LazyHStack,LazyVGrid,LazyHGridfor large collections. Regular stacks render all children immediately. - Stable IDs: All items in
List/ForEachmust conform toIdentifiablewith stable IDs. Never use array indices. - Avoid body recomputation: Move filtering and sorting to computed properties or the model, not inline in
body. - Equatable views: For complex views that re-render unnecessarily, conform to
Equatable.
HIG Alignment
Follow Apple Human Interface Guidelines for layout, typography, color, and accessibility. Key rules:
- Use semantic colors (
Color.primary,.secondary,Color(uiColor: .systemBackground)) for automatic light/dark mode - Use system font styles (
.title,.headline,.body,.caption) for Dynamic Type support - Use
ContentUnavailableViewfor empty and error states - Omit
spacing:on stacks unless a specific value is required —nil(the default) uses platform-appropriate adaptive spacing - Support adaptive layouts via
horizontalSizeClass - Provide VoiceOver labels (
.accessibilityLabel) and support Dynamic Type accessibility sizes by switching layout orientation
See references/design-polish.md for HIG, theming, haptics, focus, transitions, and loading patterns.
Writing Tools (iOS 18+)
Control the Apple Intelligence Writing Tools experience on text views with .writingToolsBehavior(_:).
| Level | Effect | When to use |
|---|---|---|
.complete | Full inline rewriting (proofread, rewrite, transform) | Notes, email, documents |
.limited | Reduced overlay-panel experience | Code editors, validated forms |
.disabled | Writing Tools hidden entirely | Passwords, search bars |
.automatic | System chooses based on context (default) | Most views |
TextEditor(text: $body)
.writingToolsBehavior(.complete)
TextField("Search…", text: $query)
.writingToolsBehavior(.disabled)
Detecting active sessions: Read isWritingToolsActive on UITextView (UIKit) to defer validation or suspend undo grouping until a rewrite finishes.
Common Mistakes
- Using
@ObservedObjectto create objects -- use@StateObject(legacy) or@State(modern) - Heavy computation in view
body-- move to model or computed property - Not using
.taskfor async work -- manualTaskinonAppearleaks if not cancelled - Array indices as
ForEachIDs -- causes incorrect diffing and UI bugs - Forgetting
@Bindable--$propertysyntax on@Observablerequires@Bindable - Over-using
@State-- only for view-local state; shared state belongs in@Observable - Not extracting subviews -- long body blocks are hard to read and optimize
- Using
NavigationView-- deprecated; useNavigationStack - Reaching for
foregroundColor(_:)whenforegroundStyle(_:)better matches semantic styling - Inline closures in body -- extract complex closures to methods
.sheet(isPresented:)when state represents a model -- use.sheet(item:)instead- Using
AnyViewfor routine branching -- type erasure hides structure and can hurt performance or identity-sensitive transitions. Use@ViewBuilder,Group, or generics unless an API genuinely needs heterogeneous view storage. See references/deprecated-migration.md - Putting
@AppStorageinside an@Observableclass --@AppStorageis a SwiftUIDynamicProperty; it only triggers view updates when used directly in aView. Inside an@Observableclass, observation tracking never sees the change. Keep@AppStoragein views, or read/writeUserDefaultsdirectly inside the@Observableclass:
// Wrong -- @AppStorage is invisible to @Observable tracking
@MainActor @Observable final class Settings {
@AppStorage("theme") var theme: String = "system" // view won't update
}
// Right -- UserDefaults read/write with a normal stored property
@MainActor @Observable final class Settings {
var theme: String {
didSet { UserDefaults.standard.set(theme, forKey: "theme") }
}
init() {
theme = UserDefaults.standard.string(forKey: "theme") ?? "system"
}
}
- Hard-coding
spacing:on every stack -- omit it to get adaptive platform spacing; only specify when the value is intentional - Treating
.copyable,.cuttable, or command-based.pasteDestination(for:action:validator:)as iOS 16/iOS 26 APIs -- they are macOS 13+ and iOS/iPadOS/Mac Catalyst 27 beta in current Apple docs. UseUIPasteboard, drag/drop, orShareLinkfor iOS 26 targets. - Treating modern defaults as formal deprecations --
#Previewis the modern preview default, butPreviewProvideris legacy rather than compiler-deprecated.EditButton,.onDelete, and.onMoveremain valid for edit-mode list workflows; use.swipeActionsfor contextual row actions.
Review Checklist
-
@Observableused for shared state models (notObservableObjecton iOS 17+) -
@Stateowns objects;let/@Bindablereceives them - Migration and availability claims checked for current platform support, especially clipboard and sharing APIs
-
NavigationStackused (notNavigationView) -
.taskmodifier for async data loading -
LazyVStack/LazyHStackfor large collections - Stable
IdentifiableIDs (not array indices) - Views decomposed into focused subviews
- No heavy computation in view
body - Environment used for deeply shared state
-
foregroundStyle(_:)used when semantic styling is preferable to a fixed color - Custom
ViewModifierfor repeated styling -
.sheet(item:)preferred over.sheet(isPresented:) - Sheets own their actions and call
dismiss()internally - MV pattern followed -- no unnecessary view models
- UI-bound
@Observablestores and view models are@MainActor-isolated - Model types passed across concurrency boundaries are
Sendable - Stack
spacing:omitted unless a specific value is required (prefer adaptive default)
References
- Architecture, app wiring, and lightweight clients: references/architecture-patterns.md
- Design polish (HIG, theming, haptics, transitions, loading, focus): references/design-polish.md
- Deprecated API migration: references/deprecated-migration.md
- Platform and sharing patterns (Transferable, clipboard availability, media, menus, macOS settings): references/platform-and-sharing.md
Related skills
More from dpearson2699/swift-ios-skills and the wider catalog.

swiftui-performance
Audit and optimize SwiftUI runtime performance—diagnose slow rendering, janky scrolling, and excessive view updates.

swiftui-uikit-interop
Bridge UIKit and SwiftUI bidirectionally with representables, hosting controllers, and state synchronization.

swiftui-webkit
Embed and control web content in SwiftUI using native WebKit APIs for iOS 26+.

tabletopkit
Build multiplayer spatial board games on visionOS with TabletopKit, handling boards, pieces, turns, and FaceTime synchronization.

tipkit
Implement Apple TipKit feature-discovery UI for iOS 17+ apps with inline tips, popovers, rules, and CloudKit sync.

vision-framework
Detect text, faces, barcodes, and objects in iOS images and video using on-device Vision framework.