TL;DR
It seems that the ContentView
below evaluates the body's if
statement before init
has run. Is there a race condition, or is my mental model out-of-order?
Kudos
A shout-out to Asperi, who provided the state-initializer equivalent that solves today's problem.
Code
Why does ContentView
display "dummy is nil"? It seems something gets closed over before the initializer sets dummy
. What is it about the second assignment that fixes things?
class Dummy { }
struct ContentView: View {
@State private var dummy : Dummy?
init() {
print("Init") // In either case, is printed before "Body"
// Using this assignment, "dummy is nil" shows on screen.
self.dummy = Dummy()
// Using this, "dummy is non-nil" shows on screen.
// From https://stackoverflow.com/questions/61650040/swiftui-initializer-apparent-circularity
// self._dummy = State(initialValue: Dummy())
}
var body: some View {
print("Body")
return ZStack {
if dummy == nil { // Decision seems to be taken
Text("dummy is nil" ) // before init() has finished.
} else {
Text("dummy is non-nil")
}
}
}
}