Modern SwiftUI patterns for building declarative, high-performance 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) - Using
NavigationStackto design navigation flows - Building View Models and data flow
- Optimizing rendering performance for lists and complex layouts
- Using Environment Values and dependency injection in SwiftUI
State Management
Property Wrapper Selection
Choose the most appropriate simple wrapper:
| Wrapper | Use Cases |
|---|---|
@State |
View-local value types (toggles, form fields, sheet presentation state) |
@Binding |
Two-way reference to parent view @State bidirectional references to |
@Observable classes + @State |
Own models with multiple properties |
@Observable classes (no wrapper) |
Read-only references passed from a parent view |
@Bindable |
Two-way binding to @Observable properties |
@Environment |
Shared dependencies injected through .environment() injected shared dependencies |
@Observable View Model (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()) ?? []
}
}
Views Using a View Model (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
Use @Environment instead of @EnvironmentObject:
// 注入 (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 the invalidation scope
Split views into small, focused structs. When state changes, only the subviews that read that state re-render:
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)
}
}
}
ViewModifiers for reusable styles
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
Together with NavigationPath use NavigationStack to implement 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
Use Lazy Containers for Large Collections
LazyVStack and LazyHStack create views only when they are visible:
ScrollView {
LazyVStack(spacing: 8) {
ForEach(items) { item in
ItemRow(item: item)
}
}
}
Stable Identifiers
In ForEach always use stable, unique IDs — avoid using array indices:
// 使用 Identifiable 协议实现或显式指定 id
ForEach(items, id: \.stableID) { item in
ItemRow(item: item)
}
Avoid Expensive Operations in body
- Never perform I/O, network requests, or heavy computation inside
bodyperform I/O, network requests, or heavy computation internally - Use
.task {}to perform asynchronous work — it is automatically canceled when the view disappears - Use
.sensoryFeedback()and.geometryGroup() - Minimize the use of
.shadow()、.blur()and.mask()in lists (List) — they trigger offscreen rendering
Equatable Conformance
For views whose body is expensive to render, implement Equatable conformance to skip unnecessary re-renders:
struct ExpensiveChartView: View, Equatable {
let dataPoints: [DataPoint] // DataPoint 必须符合 Equatable
static func == (lhs: Self, rhs: Self) -> Bool {
lhs.dataPoints == rhs.dataPoints
}
var body: some View {
// 复杂的图表渲染逻辑
}
}
Previews
Use #Preview macros combined with inline Mock data for rapid iteration:
#Preview("空状态") {
ItemListView(viewModel: ItemListViewModel(repository: EmptyMockRepository()))
}
#Preview("已加载") {
ItemListView(viewModel: ItemListViewModel(repository: PopulatedMockRepository()))
}
Anti-Patterns to Avoid (Anti-Patterns)
- Use in new code
ObservableObject/@Published/@StateObject/@EnvironmentObject— please migrate to@Observable - directly in
bodyorinitput asynchronous work in — please use.task {}or an explicit loading method - Create the view model as inside a child view that does not own the data
@State— it should be passed from the parent view - Use
AnyViewtype erasure — for conditional views, prefer@ViewBuilderorGroup - Ignore when passing data to or receiving data from an Actor
Sendablerequirements
References (References)
See skill:swift-actor-persistence for Actor-based persistence patterns.
See skill:swift-protocol-di-testing for protocol-based dependency injection (DI) and testing with Swift Testing.