SwiftUI ObservableObject Tutorial

ObservableObject is a protocol that’s part of the Combine framework. It is used within a custom class/model to keep track of the state. In this tutorial a stopwatch app is created, where the counter will be published for changes to the view. SwiftUI requires Xcode 11 and MacOS Catalina, for which the Betas can be downloaded at the Apple developer portal.

Open Xcode and either click Create a new Xcode project in Xcode’s startup window, or choose File > New > Project. In the template selector, select iOS as the platform, select the Single View App template, and then click Next. Enter SwiftUIObservableObjectTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac.

In the canvas, click Resume to display the preview. If the canvas isn’t visible, select Editor > Editor and Canvas to show it.

Add a new file to the project. Select File -> New -> File. Choose iOS -> Source -> Swift file and give the file a filename of StopWatch.swift

import Foundation
import SwiftUI
import Combine

// 1.
class Stopwatch: ObservableObject {
    // 2.
    @Published var counter: Int = 0
    
    var timer = Timer()
    
    // 3.
    func start() {
        self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
            self.counter += 1
        }
    }
    
    // 4.
    func stop() {
        timer.invalidate()
    }
    
    // 5.
    func reset() {
        counter = 0
        timer.invalidate()
    }
}
  1. The class needs to conform to the ObservableObject protocol from the Combine framework

  2. This property publish any changes to its data, so that this change is updated in the view.

  3. The start method updates the counter every second

  4. The stopwatch is stopped

  5. The couinter is reset to 0 and the stopwatch is stopped

In the Project navigator, click to select ContentView.swift. Change the code inside the ContentView struct to

struct ContentView: View {
    // 1.
    @ObservedObject var stopwatch = Stopwatch()
    
    var body: some View {
        VStack {
            HStack {
                // 2.
                Button(action: {
                    self.stopwatch.start()
                }) {
                    Text("Start")
                }
                
                Button(action: {
                    self.stopwatch.stop()
                }) {
                    Text("Stop")
                }
                Button(action: {
                    self.stopwatch.reset()
                }) {
                    Text("Reset")
                }
            }
            // 3.
            Text("\(self.stopwatch.counter)")
        }.font(.largeTitle)
    }
}
  1. The ObservedObject property wrapper “subscribes” to the Stopwatch class

  2. Three buttons are displayed. which will start,stop and reset the stopwatch.

  3. The counter value is displayed and updated from the “published” property.

Go to the preview and click the Live preview button. Start and stop the stopwatch wit h the buttons. The preview will look like this.

The source code of the SwiftUIObservableObjectTutorial can be downloaded at the ioscreator repository on Github.