Home > front end >  NavigationLink when destination's required parameter is from optional state variable
NavigationLink when destination's required parameter is from optional state variable

Time:12-08

Navigating using optional state parameters really has me stumped. The below code won't compile because selectedObject has to be nil coalesced because it's required by NextView, but I have nothing to coalesce it to. NextView requires this parameter, so an optional doesn't compile. MyObject is a struct with all required attributes, so I don't have an empty constructor. I'm using the selected state to manage when the navigation occurs, but it still won't compile because of the optional object.

struct MyView: View {
    @EnvironmentObject var model: Model
    @State var selected = false
    @State var selectedObject: MyObject? // optional because there isn't one until it's set by the child view

    var body: some View {
        NavigationLink(destination: NextView(object: $selectedObject), isActive: self.$selected) {
            EmptyView()
       }
       // ... child view that when interacted with sets the selectedObject as a binding ... //
    }
}
struct MyObject: Identifiable, Codable {
   var property1: String
   var property2: String
   // .... many more ...
}
struct NextView: View {
    @Binding var object: MyObject // required binding
    
    var body: some View {
        Text("some stuff about my object")
    }
}

CodePudding user response:

If you definitely know that selectedObject will be present in time of link activation then you can solve this case passing on-the-fly created binding, like

    NavigationLink(destination: NextView(object:
        Binding(
            get: {selectedObject!},
            set: {selectedObject = $0}
        )), isActive: self.$selected) { EmptyView()
    }
  • Related