0
0
iOS Swiftmobile~20 mins

@Published properties in iOS Swift - Mini App: Build & Ship

Choose your learning style9 modes available
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 ]  |
-------------------
Use a ViewModel class with an @Published integer property called count.
Display the current count in a Text view.
Add a button labeled 'Increase' that increments the count by 1 when tapped.
The UI should update automatically when count changes.
Starter Code
iOS Swift
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()
    }
}
Task 1
Task 2
Task 3
Solution
iOS Swift
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.

Final Result
Completed Screen
-------------------
|   Counter: 0    |
|                 |
|   [ Increase ]  |
-------------------
Tapping the 'Increase' button adds 1 to the counter number.
The displayed number updates immediately after tapping.
Stretch Goal
Add a 'Reset' button that sets the count back to zero.
💡 Hint
Add another Button below the 'Increase' button that sets viewModel.count = 0 when tapped.