Menu
Coddy logo textTech

Recap - Step Counter

Part of the Introduction to SwiftUI section of Coddy's Swift journey. Lesson 42 of 50.

challenge icon

Challenge

Hard

Build a step counter with shared data:

  • a class Activity that is an ObservableObject with a @Published steps starting at 0 and a method walk() that adds 500
  • a view GoalView that reads the activity with @EnvironmentObject and shows Goal reached! (identifier goal) once steps is 1000 or more, and Keep going (same identifier) before that
  • ContentView creates the activity with @StateObject and shows a text Steps: 0, ... (identifier steps), a Walk button that calls walk(), and GoalView(), with the activity provided to the VStack through .environmentObject

Try it yourself

import SwiftUI

@main
struct CoddyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

All lessons in Introduction to SwiftUI

Practice on your own: Swift playground