title: Presenting an Alert in SwiftUI using MVVM
body: <p>I'm trying to build an app using SwiftUI and an MVVM architecture. I'd like to have my View present an alert whenever its ViewModel deems it necessary—say, when it has a new result of some sort available from the Model. So suppose whenever the VM detects a new result it sets its <code>status</code> accordingly:</p>
  
  <p><strong>The ViewModel:</strong></p>
  
  <pre><code>enum Status {
      case idle
      case computing
      case newResultAvailable
  }
  
  class MyViewModel: ObservableObject {
  
      @Published var status = Status.idle
  
      ...
  }
  </code></pre>
  
  <p><strong>The View:</strong></p>
  
  <pre><code>struct ContentView: View {
  
      @ObservedObject var vm = MyViewModel()
  
      @State private var announcingResult = false {
          didSet {
              // reset VM status when alert is dismissed
              if announcingResult == false {
                  vm.status = .idle
              }
          }
      }
  
      var body: some View {
          Text("Hello")
          .alert(isPresented: $announcingResult) {
              Alert(title: Text("There's a new result!"),
                  message: nil,
                  dismissButton: .default(Text("OK")))
          }
      }
  }
  </code></pre>
  
  <p>Apple has designed the <code>.alert()</code> modifier to take a binding as its first argument, so that the alert is displayed whenever the bound property becomes <code>true</code>. Then, when the alert is dismissed, the bound property is automatically set to <code>false</code>.</p>
  
  <p><strong>My question is:</strong> 
  How can I have the alert appear whenever the VM's <code>status</code> becomes <code>.newResultAvailable</code>? It seems to me that that's how proper MVVM should function, and it feels very much in the spirit of all the SwiftUI WWDC demos, but I can't find a way…</p>