title: How to work with bindings when using a view model vs using @Binding in the view itself?
body: <p><code>@State</code> and <code>@Binding</code> work so well in <code>SwiftUI</code>, as long as you put all the view's data inside itself, like this:</p>
  
  <pre class="lang-swift prettyprint-override"><code>struct ColorView: View {
      @Binding public var isBlue: Bool
  
      var body: some View {
          Rectangle()
              .foregroundColor(isBlue ? .blue : .red)
              .onTapGesture {
                  self.isBlue.toggle()
          }
      }
  }
  
  struct TestView: View {
      @State var isBlue: Bool = false
  
      var body: some View {
          ColorView(isBlue: $isBlue)
      }
  }
  </code></pre>
  
  <p>It works without a problem and it's really simple. But <code>MVVM</code> says you should put all of the view's data inside a view model class, to separate UI from the model. But then you lose <code>@State</code> and <code>@Binding</code> completely. You lose this 2-way binding it seems. Sure, you can do it manually with <code>Combine</code> or something but that should not be the correct way, right? </p>
  
  <p>Whenever I try anything, <code>SwiftUI</code> is really easy and convenient when you <strong>don't</strong> use view models. Once you put everything inside a view model class, though, everything breaks down and nothing works as convenient anymore. This can't be the case, they have to had thought of that. So I'm missing something here. I'd really appreciate any help. How would you code the above's example using view models (without "hacking" anything manually)? I tried but it doesn't even compile:</p>
  
  <pre class="lang-swift prettyprint-override"><code>struct ColorView: View {
      @ObservedObject var viewModel: ViewModel
  
      class ViewModel: ObservableObject {
          // Binding or Published? Both doesn't seem to work
          @Binding var isBlue: Bool
  
          init(isBlue: Binding&lt;Bool&gt;) { // Or type Bool? But then we lose the binding
              self.$isBlue = isBlue
          }
      }
  
      var body: some View {
          Rectangle()
              .foregroundColor(viewModel.isBlue ? .blue : .red)
              .onTapGesture {
                  self.viewModel.isBlue.toggle()
          }
      }
  }
  
  struct TestView: View {
      @ObservedObject var viewModel: ViewModel
  
      class ViewModel: ObservableObject {
          @Published var isBlue: Bool = false // We would need a @State here, but then we lose @Published
      }
  
      var body: some View {
          ColorView(viewModel: .init(isBlue: /* ??? */)) // How to pass a binding here`
      }
  }
  </code></pre>
  
  <p>Do I think of this the wrong way?</p>
  
  <p>Thanks!</p>