Intermediate 24 min readModule: Module 10: SwiftUI Declarative UI & MVVM State Architecture
SwiftUI Declarative UI & @Observable State Management
Build modern, reactive user interfaces with SwiftUI, the Swift 6 Observation framework (`@Observable`), View composition, and unidirectional state flow.
What You Will Learn in This Lesson
- Declarative UI paradigm: Describing WHAT the interface should look like based on state
- The modern Swift Observation framework: `@Observable` classes
- State property wrappers: `@State` (local view state) and `@Binding` (two-way binding)
- Unidirectional Data Flow (UDF) in clean SwiftUI architectures
Introduction & Core Concept
SwiftUI is Apple's modern declarative UI framework across all Apple platforms. Unlike legacy imperative UIKit (where developers manually created, positioned, and updated view hierarchies in response to events), SwiftUI views are lightweight structs that declare what the UI should look like for a given state. When state changes, SwiftUI automatically recomputes only the affected UI components.
WHY DOES THIS MATTER IN THE REAL WORLD?
Declarative UI development cuts UI codebases by 60% and eliminates state synchronization bugs. The modern '@Observable' macro in Swift 6 eliminates boilerplate Combine publishers ('@Published') and provides granular view invalidation.
Syntax & Structure
swift
@Observable class ViewModel { var count = 0 } struct CounterView: View { @State private var vm = ViewModel() var body: some View { ... }}SwiftUI View Architecture with the @Observable Macro
swiftswift
123456789101112131415161718192021222324252627282930313233343536373839404142// SwiftUI Declarative Architecture with @Observableimport Foundation// 1. Modern Swift Observation ViewModelclass CourseListViewModel {var searchQuery: String = ""var courses: [String] = ["Swift 6 Systems Architecture","Kotlin Multiplatform & Coroutines","Linux Kernel & Ubuntu Shell","Rust Systems & Concurrency"]var filteredCourses: [String] {if searchQuery.isEmpty {return courses} else {return courses.filter { $0.localizedCaseInsensitiveContains(searchQuery) }}}}// Simulated SwiftUI View structstruct CourseListView {var viewModel = CourseListViewModel()func renderUI() {print("=== SwiftUI View Rendered ===")print("Search Term: '\(viewModel.searchQuery)'")print("Courses Displayed (\(viewModel.filteredCourses.count)):")for course in viewModel.filteredCourses {print(" [Card] 📚 \(course)")}}}var view = CourseListView()view.renderUI()print("\n--- User Types 'Swift' into Search Field ---")view.viewModel.searchQuery = "Swift"view.renderUI()
Line-by-Line Technical Breakdown
1The @Observable Macro: Introduced in Swift 5.9 / Swift 6, `@Observable` uses Swift Macros to track property access at runtime. When a view accesses a property in its `body`, SwiftUI subscribes specifically to that property, avoiding unnecessary re-renders when unrelated properties change.
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[SWIFT]
SWIFT SOURCE EDITOR
Interactive Live CodeCommon Mistakes & How to Avoid Them
#1: Performing heavy network or disk I/O directly inside the computed `var body: some View` property.
View bodies can be executed dozens of times per second during animations. Bodies must remain pure, lightweight functions of state.
Incorrect / Antipattern
var body: some View { let data = fetchFromNetwork(); Text(data) }Correct / Professional Solution
var body: some View { Text(viewModel.data).task { await viewModel.load() } }Industry Best Practices & Professional Standards
- Keep View structs small, composable, and focused on presentation.
- Use `@Observable` classes for complex business logic and ViewModel state.
- Use the `.task` modifier for lifecycle-aware asynchronous data fetching in SwiftUI views.
Lesson Summary & Core Takeaways
- SwiftUI is a declarative framework where the UI is a function of state: `UI = f(State)`.
- The `@Observable` framework tracks state changes with fine-grained reactivity.
- Views are lightweight immutable structs that are recreated on state mutations with zero performance penalty.