TL;博士
以下似乎ContentView
评估了之前运行的主体if
声明。init
是否存在竞争条件,或者我的心理模型是否有问题?
荣誉
向 Asperi 致敬,他提供了解决当今问题的等效状态初始化器。
代码
为什么ContentView
显示“dummy is nil”?似乎有些东西在初始化设置之前dummy
就被关闭了。解决问题的第二个任务是什么?
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")
}
}
}
}