【发布时间】:2020-09-18 14:53:52
【问题描述】:
我有一个带有State 变量的视图,它是一个Optional。我通过首先检查可选变量是否为 nil 来渲染视图,如果不是,则强制展开它并使用 Binding 将其传递到子视图中。
但是,如果我在值和 nil 之间切换可选变量,应用程序会崩溃,并且我会在函数 BindingOperations.ForceUnwrapping.get(base:) 中得到 EXC_BAD_INSTRUCTION。如何仅显示“Nil”Text 视图来获得视图的预期功能?
struct ContentView: View {
@State var optional: Int?
var body: some View {
VStack {
if optional == nil {
Text("Nil")
} else {
TestView(optional: Binding($optional)!)
}
Button(action: {
if optional == nil {
optional = 0
} else {
optional = nil
}
}) {
Text("Toggle")
}
}
}
}
struct TestView: View {
@Binding var optional: Int
var body: some View {
VStack {
Text(optional.description)
Button(action: {
optional += 1
}) {
Text("Increment")
}
}
}
}
【问题讨论】:
标签: exception swiftui optional