-2

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?

  • See [Value and Reference Types](https://developer.apple.com/swift/blog/?id=10) – pawello2222 Jul 06 '20 at 22:42
  • just change the variable in your stopwatch screen and check what happens, then you can answer your question yourself. if it is by value (a copy) then the value just changes in one screen. – Chris Jul 07 '20 at 05:36

1 Answers1

0

reference. since StopWatch is a class.

annotations, e.g.; @ObservedObject, don't come into play unless otherwise specified, e.g.; $ operator.

Jim lai
  • 1,224
  • 8
  • 12