title: How to optionally pass in a Binding in SwiftUI?
body: <p>I have a view that internally manages a @State variable that keeps track of the current index. So something like:</p>
  
  <pre class="lang-swift prettyprint-override"><code>struct ReusableView: View {
  
      @State var index: Int = 0
  
      var body: some View {
          Text("The index is \(self.index)"
          // A button that changes the index
      }
  
  }
  </code></pre>
  
  <p>This view is going to be reused throughout the app. Sometimes the parent view will need access to the index, so I refactored it like this:</p>
  
  <pre class="lang-swift prettyprint-override"><code>struct ParentView: View {
  
      @State var index: Int = 0
  
      var body: some View {
        ReusableView($index)
      }
  
  }
  
  struct ReusableView: View {
  
      @Binding var index: Int
  
      var body: some View {
          Text("The index is \(self.index)"
          // A button that changes the index
      }
  
  }
  
  </code></pre>
  
  <h3>The problem</h3>
  
  <p>I don't want to enforce the parent view to <strong>always</strong> keep the state of the index. In other words, I want to optionally allow the parent view to be in charge of the state variable, but default to the Reusable View to maintain the state in case the parent view doesn't care about the index.</p>
  
  <h3>Attempt</h3>
  
  <p>I tried somehow to initialize the binding on the reusable view in case the parent view doesn't provide a binding:</p>
  
  <pre class="lang-swift prettyprint-override"><code>struct ReusableView: View {
  
      @Binding var index: Int
  
      init(_ index: Binding&lt;Int&gt;? = nil) {
          if index != nil {
              self._index = index
          } else {
              // TODO: Parent didn't provide a binding, init myself.
              // ?
          }
      }
  
      var body: some View {
          Text("The index is \(self.index)"
          // A button that changes the index
      }
  
  }
  </code></pre>
  
  <p>Thank you!</p>