SwiftUI Patterns
Declarative, performant SwiftUI on Apple platforms: Observation framework, composition, type-safe navigation. Detalhes em references/.
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
- Injecting dependencies via environment values
Core Principles
- Simplest wrapper that fits —
@Statelocal,@Bindingup,@Observablemodel,@Environmentshared - Small subviews — only the view reading changed state re-renders
- Type-safe routing —
NavigationStack+NavigationPath+Destinationenum - Lazy + stable IDs —
LazyVStack, never index-basedForEach - No work in
body— async in.task {}, cheap modifiers in lists
Example
@Observable
final class ItemListViewModel {
private(set) var items: [Item] = []
func load() async { items = (try? await repository.fetchAll()) ?? [] }
}
References
references/state-management.md— wrapper table, @Observable VM, environmentreferences/composition.md— subviews, ViewModifier, previewsreferences/navigation.md— Router, Destination enum, RootViewreferences/performance.md— lazy containers, IDs, Equatable, anti-patterns
Checklist
-
@Observable, notObservableObject/@StateObjectin new code - Views split so invalidation stays local; no
AnyView -
NavigationStack(path:)withnavigationDestination(for:) - Lists lazy with stable IDs; no I/O in
body -
#Previewwith mock repos for empty + loaded states