How To Set Values To Binding Variable

I have a model struct

struct Temp {
var cityUrlId: String {
    get {
      print(_cityUrlId)
      print("gettting="+StringTool.nullToString(_cityUrlId).trim())
      
      return _cityUrlId
    }
    set(newValue) {
      print("newvalue="+newValue)
      _cityUrlId = _cityUrlId
      print("_cityUrlId="+_cityUrlId!)
    }
  }
}

The parent view has a state variable e.g.

@State var temp: Temp

and a child view as a new window with @Binding var temp: Temp

My question is that when the temp in child view sets a value for cityUrlId property, it's ok. but once i set a new value in the parent view, the getter returns nil. why is that?

is the solution for this have to be a class for Temp instead of a struct?

It would be easier if you showed the complete code. We miss a lot to be able to replicate.

Where is StringTool defined ?

In the meanwhile, you may have a look here: https://stackoverflow.com/questions/65209314/what-does-the-underscore-mean-before-a-variable-in-swiftui-in-an-init

It explains the use of different properties in a Binding var

Given one variable declaration, @Binding var momentDate: Date, you can access three variables:

  • self._momentDate is the Binding struct itself.
  • self.momentDate, equivalent to self._momentDate.wrappedValue, is a Date. You would use this when rendering the date in the view's body.
  • self.$momentDate, equivalent to self._momentDate.projectedValue, is also the Binding. You would pass this down to child views if they need to be able to change the date.

Please ignore StringTool. its just a helper tool to ensure that if it's a nil, it will return "". In the child view i did it like this

init(temp: Binding<Temp?>) {
    _temp = temp
}

in the parent view it looks like this

ChiildView(temp: $temp)

when i dismiss the child view, i want to set the property cityUrlId in the parent view which is @State

Can't you really show the entire code so that we can reproduce ?

How To Set Values To Binding Variable
 
 
Q