SwiftUI: The Core Idea – Swift
Declarative interfaces: views as a function of state.
SwiftUI describes interfaces declaratively: you do not say “add a button and change its text later”, but “this is what the interface looks like for this state”. When the state changes, SwiftUI automatically recomputes the affected parts. Views are lightweight structs that conform to the View protocol with the property body.
import SwiftUI
struct ZaehlerView: View {
@State private var zaehler = 0 // state: change -> body recomputed
var body: some View {
VStack(spacing: 16) {
Text("Counter: \(zaehler)")
.font(.title)
Button("Increment") { zaehler += 1 }
.buttonStyle(.borderedProminent)
}
.padding()
}
}
@main
struct MeineApp: App {
var body: some Scene {
WindowGroup { ZaehlerView() }
}
}Layout is created by nesting containers (VStack, HStack, ZStack, List). Modifiers (.font, .padding, .foregroundStyle) change a view and return a new one, so their order matters. With $ you pass on a binding: a two-way connection to the state, e.g. for input fields.
struct NamenListe: View {
@State private var namen = ["Ada", "Linus"]
@State private var neuerName = ""
var body: some View {
VStack {
HStack {
TextField("Name", text: $neuerName) // $ = binding
.textFieldStyle(.roundedBorder)
Button("Add") {
guard !neuerName.isEmpty else { return }
namen.append(neuerName)
neuerName = ""
}
}
List(namen, id: \.self) { name in
Text(name)
}
}
.padding()
}
}For shared models, since iOS 17 people use the @Observable macro (framework Observation): SwiftUI remembers which properties a view reads and updates it in a targeted way. Older projects use ObservableObject with @Published, @StateObject, and @ObservedObject.
import Observation
@Observable
class EinkaufsModell {
var artikel: [String] = []
func hinzufuegen(_ a: String) { artikel.append(a) }
}
struct EinkaufsView: View {
@State private var modell = EinkaufsModell() // owns the model
var body: some View {
VStack {
Button("Milk") { modell.hinzufuegen("Milk") }
Text("\(modell.artikel.count) items")
}
}
}#Preview { ZaehlerView() } shows the view live in the Xcode canvas. The rule for state is: whoever owns the truth uses @State; whoever may only edit it gets a @Binding.body (this triggers an infinite loop of recomputations); only in response to events such as button actions or in .task. Also: @State belongs on the view that owns the value, not on every child view.