title: Is there a way to bind an optional to a Toggle / Slider with SwiftUI
body: <p>I have a <code>UInt?</code> (optional) property in my data model that I am trying to bind to a <code>Toggle</code> and <code>Slider</code> with SwiftUI. I am trying to get to something like this:</p>
  
  <ul>
  <li><code>maximumRingsShownCount</code> have value 4 (not nil), then the toggle should be <strong>on</strong> and the value bound to the slider.</li>
  <li><code>maximumExpandedRingsShownCount</code> value is nil, then the toggle should <strong>off</strong> and the slider is not shown.</li>
  </ul>
  
  <p><a href="https://i.stack.imgur.com/U8yNI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U8yNI.png" alt="Toggle and Sliders rendered with SwiftUI"></a></p>
  
  <p>I am facing 2 issues here:</p>
  
  <ol>
  <li>It looks like we cannot have optional bindings (for the Slider)</li>
  <li>Is it possible to have a transformer to transform the optional to boolean (for the Toggle)?</li>
  </ol>
  
  <p>So far, in my view I declared 2 properties in addition to my model:</p>
  
  <pre><code>@ObjectBinding var configuration: SunburstConfiguration
  
  @State private var haveMaximumRingsShownCount: Bool = false
  @State private var haveMaximumExpandedRingsShownCount: Bool = false
  </code></pre>
  
  <p>And my view body contains (for each property):</p>
  
  <pre><code>Toggle(isOn: $haveMaximumRingsShownCount) {
      Text("maximumRingsShownCount")
  }
  if haveMaximumRingsShownCount {
      VStack(alignment: .leading) {
          Text("maximumRingsShownCount = \(config.maximumRingsShownCount!)")
              Slider(value: .constant(4 /* no binding here :( */ ))
          }
      }
  }
  </code></pre>
  
  <p>The UI layout is correct but I still have the issues mentioned above because:</p>
  
  <ol>
  <li>The <code>haveMaximumRingsShownCount</code> state is not bound to my <code>config.maximumRingsShownCount</code> model being nil or not</li>
  <li>The slider is currently just displaying a constant and not bound to the unwrapped <code>config.maximumRingsShownCount</code> property</li>
  </ol>
  
  <p>Any ideas on how to solve these issue with optionals?</p>
  
  <p>[ This can be reproduced in the sample code at <a href="https://github.com/lludo/SwiftSunburstDiagram" rel="nofollow noreferrer">https://github.com/lludo/SwiftSunburstDiagram</a> ]</p>