Consider a simple SwiftUI class to implement a countdown timer:
class Stopwatch: ObservableObject {
@Published var counter: Int = 0
var timer = Timer()
func start() {
self.timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
self.counter += 1
}
}
}
I create an instance of this stopwatch in a simple view with a 'Start' button. On this view there is also a button (nav link) to move to a second screen. I pass an instance of the stopwatch class to the second screen.
struct ContentView: View {
@ObservedObject var stopwatch = Stopwatch()
var body: some View {
NavigationView {
VStack {
Text("Counter: \(self.stopwatch.counter) ")
Button(action: {
self.stopwatch.start()
}) {
Text("Start")
}
NavigationLink(destination: Screen2(stopwatch: stopwatch)) {
Text("Next screen")
}
}
}
}
}
Here is the second screen:
struct Screen2: View {
@ObservedObject var stopwatch: Stopwatch
var body: some View {
VStack {
Button(action: {
self.stopwatch.stop()
}) {
Text("Stop")
}
Text("\(self.stopwatch.counter)")
}
}
}
This all works great. After I start the stopwatch on the first screen, if I move to the second screen the stopwatch continues to update the Text view in the second screen.
Newbie question: When the 'stopwatch' variable inside 'ContentView' is passed to 'Screen2' via the NavigationLink view, is that variable being passed by value or by reference?