Build: Counter Screen
A simple screen that shows a number and a button to increase it. The number updates automatically using @Published property.
Target UI
------------------- | Counter: 0 | | | | [ Increase ] | -------------------
------------------- | Counter: 0 | | | | [ Increase ] | -------------------
import SwiftUI class CounterViewModel: ObservableObject { // TODO: Add @Published property here } struct CounterView: View { @StateObject private var viewModel = CounterViewModel() var body: some View { VStack(spacing: 20) { // TODO: Display count here // TODO: Add Increase button here } .padding() } } struct CounterView_Previews: PreviewProvider { static var previews: some View { CounterView() } }
import SwiftUI class CounterViewModel: ObservableObject { @Published var count = 0 } struct CounterView: View { @StateObject private var viewModel = CounterViewModel() var body: some View { VStack(spacing: 20) { Text("Counter: \(viewModel.count)") .font(.largeTitle) .accessibilityLabel("Current count") Button("Increase") { viewModel.count += 1 } .buttonStyle(.borderedProminent) .accessibilityLabel("Increase count button") } .padding() } } struct CounterView_Previews: PreviewProvider { static var previews: some View { CounterView() } }
We created a CounterViewModel class that conforms to ObservableObject. Inside it, the @Published property count holds the current number. When count changes, SwiftUI automatically updates any views observing it.
In CounterView, we use @StateObject to keep an instance of the view model. The Text view shows the current count by reading viewModel.count. The Button increments count when tapped.
This setup makes the UI update automatically without manual refresh calls, demonstrating the power of @Published properties in SwiftUI.
------------------- | Counter: 0 | | | | [ Increase ] | -------------------
@Published in SwiftUI?@Published property inside an ObservableObject class?model.count = 5 is executed?
class Model: ObservableObject {
@Published var count: Int = 0
}
let model = Model()
model.$count.sink { print("Count changed to \($0)") }class Model: ObservableObject {
@Published var name: String
init() {
name = ""
}
}
let model = Model()
model.name = "Alice"@Published property updates a label text automatically. Which of the following is the best way to connect the @Published property to the UI?Pass the test and this pattern moves unknown