abdel-17
(Abdelrahman)
1
I have a button that switches my tic-tac-toe game from pve to pvp.
struct SwitchGameModeButton: View {
@Binding var isPVE: Bool
@Binding var willReset: Bool
var body: some View {
Button {
isPVE.toggle()
print("isPVE after toggling: \(isPVE)")
willReset = true
} label: { // irrelevant
}
}
}
isPVE and willReset are @State variables passed down to GridView.
/// A view that displays a tic-tac-toe grid.
struct GridView: View {
/// True iff this grid will reset.
@Binding var willReset: Bool
/// True iff the opponent is the AI.
let isPVE: Bool
var body: some View {
// stuff
.onChange(of: willReset) { willReset in
guard willReset else { return }
self.willReset = false
Task { await resetWithAnimation() }
}
}
/// Resets the grid, updating the UI state with animation.
func resetWithAnimation() async {
// reseting stuff unrelated to `isPVE`.
print("isPVE in reset: \(isPVE)")
// stuff that relies on `isPVE`.
}
This surprisingly leads to inverted values for isPVE!
isPVE after toggling: false
isPVE in reset: true
abdel-17
(Abdelrahman)
2
I managed to fix this by using a shared ViewModel class instead of passing bindings to state variables, but this still feels very wrong. Maybe it's a bug.