I've a SwiftUI View which requires a Binding<Model> for initialization. That model needs to be passed from a List, when user selects it. The selection parameter in a list initializer requires that model be optional, so the actual data type is Binding<Model?>.
Now how do I unwrap this optional and pass it to my View?
Here's how I tried to solve it by writing a simple wrapper view.
struct EditModelViewWrapper: View {
@Binding var selectedModel: Model?
@State var temperorayModel: Model = DataModel.placeholder
init(selectedModel: Binding<Model?>) {
self._selectedModel = selectedModel
}
var body: some View {
if selectedModel == nil {
Text("Kindly select a value in the list to start editing.")
} else {
EditModelView(model: boundModel)
}
}
var boundModel: Binding<Model> {
temperorayModel = $selectedModel.wrappedValue!
return $temperorayModel
}
}
When I run this code, I get the following warning at the line, where I set value to temperoryModel.
Modifying state during view update, this will cause undefined behavior.
PS: I don't want to pause an Optional to my View and check it inside for two reasons. It will require a lot of nil checks inside the view and I have to update a lot of other files in my app, where I have used that view.