ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Swift Tutorial• 7 min read

SwiftUI & Declarative State Management

The View protocol, @State, @Binding, and declarative body layouts

SwiftUI is Apple’s modern declarative UI framework across all Apple platforms, where the user interface is a direct function of state.

Core SwiftUI State Property Wrappers

@State: Manages local private mutable state within a single view. When state changes, SwiftUI automatically re-renders the affected view hierarchy.

@Binding: Creates a two-way connection to state owned by an ancestor view (e.g. toggles, text fields).

VStack, HStack, ZStack: Stacks views vertically, horizontally, or overlapping along the Z-axis.

Interactive Counter View in SwiftUI
import SwiftUI

struct CounterView: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 20) {
            Text("Score: \(count)")
                .font(.largeTitle)
                .bold()

            HStack {
                Button("Decrement") { count -= 1 }
                    .buttonStyle(.bordered)
                Button("Increment") { count += 1 }
                    .buttonStyle(.borderedProminent)
            }
        }
        .padding()
    }
}
Modifying @State automatically invalidates and redraws the body.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which property wrapper in SwiftUI manages local mutable state inside a View and triggers an automatic UI redraw when modified?