Hi All,
Hope everyone is well. Just trying to get my head around property observers didSet and willSet. I get how to implement them, but not how to actually use them in a practical way.
There are plenty of examples online, but most of these simply print out the result of “oldVaule” and “newValue” in a playground demo.
Is it possible to show a practical demo of how to actually use the oldValue and newValue within the actual code itself?
I have a case where I wish to swap the value in two picker views after I save the values from the Picker.
The first value is a departure point, the second is arrival.
I also use a variable called “origin” that i use as a container to temporarily store the value of selectedDeparture.
I then set selectedDeparture = selectedArrival.
Finally i set the selected arrival to origin:
selectedArrival = self.origin
So in effective one I have added the departure and arrival airports to the array, I reverse their values as a return flight ready for the next user selection.
Is there are smarter way I can do this somehow using property observers?
Many thanks
Tariq
@State private var selectedDeparture: Int = 0
@State private var selectedArrival = 0
@State private var origin: Int = 0
Section {
Picker("Departure", selection: $selectedDeparture ) {
ForEach (0..<schedule.airports.count) {
Text(self.schedule.airports[$0].iATA)
}
}
Picker("Destination", selection: $selectedArrival) {
ForEach (0..<schedule.airports.count) {
Text(self.schedule.airports[$0].iATA)
}
}
}
The schedule.airports[$0}.iATA is a 3 letter code representing the airport, eg JFK.
Below the pickers in my code I have a button that will add the selected value from the pickers.
Button(action: {schedule.addFlight(number: flightNumber, goingFrom: schedule.airports[selectedDeparture], goingTo: schedule.airports[selectedArrival])
self.flightNumber = ""
self.origin = self.selectedDeparture
self.selectedDeparture = self.selectedArrival
self.selectedArrival = self.origin
dismissSheet = false}, label: {
Text("Add")
})