1

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.

imthath
  • 1,353
  • 1
  • 13
  • 35
  • 1
    Does [this](https://stackoverflow.com/questions/58297176/how-can-i-unwrap-an-optional-value-inside-a-binding-in-swift/58297743#58297743) help? – Sweeper Oct 31 '20 at 13:37
  • Yes. the problem is we are facing similar problems in different places in SwiftUI and each one understands the problem differently. Hence I was not able to search and find that post. – imthath Nov 01 '20 at 11:38

1 Answers1

1

You don't need boundModel for such body, use instead

var body: some View {
    if selectedModel == nil {
        Text("Kindly select a value in the list to start editing.")
    } else {
        EditModelView(model: Binding(selectedModel)!)   // << here !!
    }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690