How do I copy a variable in Swift/SwiftUi

Hi, I am making this sort of book logging app where you can enter how long you read a book and it will save it in the log, but I ran into a little problem. On the settings page, you can set a daily goal, and you enter the daily goal using a stepper. The problem is I have a binding on that stepper, and I want to reference that later so that the stepper where you enter your time will start at your daily goal. How can I do this? Here is of my code:

struct ContentView: View {
  @AppStorage("hoursGoal") var hoursGoal = 0
  @AppStorage("minutesGoal") var minutesGoal = 0
  @State var hoursLogged = 0
  @State var minutesLogged = 0
  

List {
  Section{
    Stepper {
        Text("\(hoursGoal)h \(minutesGoal)m")
   } onIncrement: {
     //increment by thirty minutes when you step up
     minutesGoal += 30
     if (minutesGoal == 60) {
       hoursGoal += 1
       minutesGoal = 0
     }
   } onDecrement: {
     //decrement by thirty minutes when you step down
     minutesGoal -= 30
     if (minutesGoal == -30) {
       hoursGoal -= 1
       minutesGoal = 30
     }
   }
 } header: {
  Text("Daily Goal")
}
}

//pretend this next section is a separate page
Section {
  hoursLogged = hoursGoal
  minutesLogged = minutesGoal
  
  //stepper for hours entered
  Stepper("\(hoursLogged) hours", value: $hoursLogged)
  //stepper for minutes entered
  Stepper("\(minutesLogged) minutes, value: $minutesLogged)
}

When I run this It doesn't work, someone please help, thanks.

I am assuming this is where the problem lies:

hoursLogged = hoursGoal
minutesLogged = minutesGoal

You shouldn't modify @State variables inside a view's body property or content closure.

Do this in an onAppear(_:) modifier or similar. That's what might be causing the issue.


Also, you haven't shown enough code to understand how things are connected. Where is the "next page" Section located? Is it in ContentView?

Then yes, move this variable copying to an action closure.

You could either put this in an onAppear(_:) modifier on the Section, or if you have a Button that goes to this next page, put it in its action.

How do I copy a variable in Swift/SwiftUi
 
 
Q