I'm looking for a clean solution to resolve this SwiftUI challenge.
The following code compiles but do not work since @State property is outside the ContentView scope.
import SwiftUI
struct ContentView: View {
  var state: LocalState?
  
  var body: some View {
    if let state = state {
      Toggle("Toggle", isOn: state.$isOn)
    }
  }
}
extension ContentView {
  struct LocalState {
    @State var isOn: Bool
  }
}
struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    VStack {
      ContentView(
        state: .init(isOn: false)
      )
      .border(Color.red)
      
      ContentView()
        .border(Color.red)
    }
    
  }
}
The following code doesn't compile since the following reasons:
Value of optional type 'ContentView.LocalState?' must be unwrapped to refer to member 'isOn' of wrapped base type 'ContentView.LocalState'
It seems that $ in $state.isOn refer to the original state and not to the unwrapped one.
import SwiftUI
struct ContentView: View {
  @State var state: LocalState!
  
  var body: some View {
    if let state = state {
      Toggle("Toggle", isOn: $state.isOn)
    }
  }
}
extension ContentView {
  struct LocalState {
    var isOn: Bool
  }
}
struct ContentView_Previews: PreviewProvider {
  static var previews: some View {
    VStack {
      ContentView(
        state: .init(isOn: false)
      )
      .border(Color.red)
      
      ContentView()
        .border(Color.red)
    }
  }
}
What I do NOT want is:
- use of failable initializer in ContentView.
- move isOnproperty outsideLocalState.
How can I achieve those?
 
     
     
     
    