0
0
iOS Swiftmobile~20 mins

ObservableObject protocol 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 when changed using ObservableObject and @Published.
Target UI
-------------------
|   Counter App   |
-------------------
|                 |
|       0         |
|                 |
|   [ Increase ]  |
-------------------
Create a class that conforms to ObservableObject.
Add a @Published integer property to hold the count.
Build a SwiftUI view that observes this object.
Display the current count in a Text view.
Add a Button that increments the count when tapped.
Starter Code
iOS Swift
import SwiftUI

// TODO: Create ObservableObject class here

struct CounterView: View {
    // TODO: Add @StateObject or @ObservedObject property here

    var body: some View {
        VStack(spacing: 20) {
            // TODO: Display count here

            // TODO: Add button to increase count
        }
        .padding()
    }
}

struct CounterView_Previews: PreviewProvider {
    static var previews: some View {
        CounterView()
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
iOS Swift
import SwiftUI

class CounterModel: ObservableObject {
    @Published var count = 0
}

struct CounterView: View {
    @StateObject var model = CounterModel()

    var body: some View {
        VStack(spacing: 20) {
            Text("\(model.count)")
                .font(.largeTitle)
                .accessibilityLabel("Current count")

            Button("Increase") {
                model.count += 1
            }
            .buttonStyle(.borderedProminent)
            .accessibilityLabel("Increase count button")
        }
        .padding()
    }
}

struct CounterView_Previews: PreviewProvider {
    static var previews: some View {
        CounterView()
    }
}

We created CounterModel as a class that follows ObservableObject. It has a @Published property count that SwiftUI watches for changes.

In CounterView, we use @StateObject to create and keep the model alive. The view shows the current count in a large font.

The button calls a closure that increases count. Because count is @Published, the view updates automatically.

We added accessibility labels for better support.

Final Result
Completed Screen
-------------------
|   Counter App   |
-------------------
|                 |
|       0         |
|                 |
|   [ Increase ]  |
-------------------
Tapping the 'Increase' button adds 1 to the number shown.
The number updates immediately without needing to reload the screen.
Stretch Goal
Add a 'Reset' button that sets the count back to zero.
💡 Hint
Add another Button below the 'Increase' button that sets model.count = 0 when tapped.