title: How to make a SwiftUI NavigationLink conditional based on an Optional Object?
body: <p>Let’s say I have a model class <code>Ball</code>, that conforms to the <code>ObservableObject</code> protocol, and I define an optional instance of it (<code>var ball: Ball?</code>).</p>
  <p>Is there a way to trigger a <code>NavigationLink</code> to display its <code>destination</code> view based on setting the value of the optional instance? So when I <code>self.ball = Ball()</code>, a <code>NavigationLink</code> will trigger?</p>
  <p>One problem seems to be that an optional (<code>Type?</code>) can’t be an <code>@ObservedObject</code>.</p>
  <p>The other problem seems to be that the <code>isActive:</code> parameter for <code>NavigationLink</code> can only take a <code>Binding&lt;Bool&gt;</code>.</p>
  <pre class="lang-swift prettyprint-override"><code>/// Contrived minimal example to illustrate the problem.
  include SwiftUI
  
  class Ball: ObservableObject {
    @Published var colour: String = &quot;red&quot;
    // ...
  }
  
  struct ContentView: View {
    // this won’t trigger view updates when it’s set because it’s not observed:
    var ball: Ball?
  
    // this line won’t compile:
    @ObservedObject var observedBall: Ball?
    //  Property type 'Ball?' does not match that of the
       // 'wrappedValue' property of its wrapper type 'ObservedObject'
  
    var body: some View {
      NavigationView {
        VStack {
          // I want this to navigate to the ballView when isActive becomes true,
          // but it won’t accept the test of nil state on the optional value:
          NavigationLink(
            destination: BallView(ball: self.ball), isActive: self.ball != nil
          ) {
            EmptyView()
          } //  compiler error because `self.ball != nil` isn’t valid for `isActive:`
  
          // Button user taps to set the `ball`,
          // which I want to trigger the BallView to be shown.
          Button(action: { self.ball = Ball() }, label: { Text(&quot;Show Ball&quot;) })
        }
      }
    }
  }
  
  struct BallView: View {
    @ObservedObject var ball: Ball
    // typical view stuff here ...
  }
  </code></pre>