今天早些时候,我发生了一些(无法解释的)崩溃,并将代码简化为以下所示。崩溃消失了,但我不确定100%。下面的代码是否是在枚举数组上创建Binding的正确方法?如果是的话,可以简化此代码吗?
import SwiftUI
enum TheEnum: Hashable {
case one(Int), two(Float)
}
class TestModel : ObservableObject {
@Published var enumArray = [TheEnum.one(5), TheEnum.two(6.0)]
}
struct ContentView: View {
@ObservedObject var testModel = TestModel()
var body: some View {
HStack {
ForEach(testModel.enumArray, id: \.self) { value -> AnyView in
switch value {
case .one(var intVal):
let b = Binding(get: {
intVal
}) {
intVal = $0
}
return AnyView(IntView(intVal: b))
case .two(var floatVal):
let b = Binding(get: {
floatVal
}) {
floatVal = $0
}
return AnyView(FloatView(floatVal: b))
}
}
}
}
}
struct IntView: View {
@Binding var intVal: Int
var body: some View {
Text("\(intVal)")
}
}
struct FloatView: View {
@Binding var floatVal: Float
var body: some View {
Text("\(floatVal)")
}
}