in this code I want to change two picker values when they are same to remain this two different from each other. I try to use swap but that’s not working properly.
for example : when first picker value is one and second is two, when I try to change second value to "one", value immediately change to one and first picker become two!
struct ContentView: View {
@State private var list = ["one","two","three","four","five"]
@State private var from: String = "one"
@State private var from: String = "two"
var body: some View {
VStack {
Picker("",selection: $from) {
ForEach(list, id: .self) { item in
Text(item)
}
}
.pickerStyle(.menu)
.padding(.trailing)
.onChange(of: from) { newValue in
if newValue == to {
(to,from) = (from, to)
}
}
Picker("",selection: $to) {
ForEach(list, id: .self) { item in
Text(item)
}
}
.pickerStyle(.menu)
.padding(.trailing)
}
}
}
I’m using this tuple solution for another section of the app but in this part that’s not working :
(from, to) = (to, from)
how can I perform immediately swap this two values when for example to going to the same with from?
2
Answers
still not 100% sure what you are trying to do, but it may be something like this,
as shown in this example code using helper vars:
I think there is a connection that is missing. You state
If you swap 2 equal values you get 2 equal values.
Assumption:
What It seems you want is a solution for the standard interview question of swapping 2 values.
The way to do this is
Now your result is
y=1 and x=2
You need that
temp
variable to hold the value of one of them, while you are swapping values.Now, if we ge back to your statement, the fallacy is in waiting for the values to become equal.
When you click on the new item the change is being made immediately, there is no way to retrieve what the value was previously.
The only way to achieve a "swapping" is to determine if there is a need to swap before the "source of truth" changes.
You can achieve this setup in SwiftUI with an
ObservableObject
Then your
View
would look like this