See below playground code:
The bottom
I would not have expected
Where is my mental model wrong?
(Xcode 12.0)
Code Block swift import SwiftUI import PlaygroundSupport struct InnerView: View { @Binding var text: String @State private var startedChange = false var body: some View { Text("Hello").onAppear { if !self.startedChange { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { self.text = "cat" } DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { self.text = "cheetah" } self.startedChange = true } } } } struct ContentView: View { @State private var animalName = "dog" var body: some View { VStack { InnerView(text: $animalName) Text(animalName) } } } PlaygroundPage.current.setLiveView(ContentView())
The bottom
Code Block swift Text(animal.name)
alternates irregularly between "cat" and "cheetah," in an infinite loop of race conditions. I expected the text to change to "cat" after one second and then "cheetah" after another.I would not have expected
Code Block swift @State private var startedChange = false
to be initialized more than once.Where is my mental model wrong?
(Xcode 12.0)