title: Using view models in SwiftUI without allocation overhead
body: <h3>Using View Models in <em>SwiftUI</em></h3>
  <p>For a clean separation of concerns, I want to use my <em>SwiftUI</em> views with view models.</p>
  <p>I have two views, a <code>ListView</code> and a <code>DetailView</code> where the first pushes the latter when any list item is tapped – a classic navigation view.</p>
  <p>I define a <code>viewModel</code> property on my <code>DetailView</code> as follows and mark it as an observed object in order to update the view when any of its published properties change:</p>
  <pre><code>struct DetailView: View {
      @ObservedObject var viewModel: DetailViewModel
  
      var body: some View { 
          Text(viewModel.text)
      }
  }
  </code></pre>
  <p>This approach requires me to pass a <code>viewModel</code> to the <code>DetailView</code>'s initializer when I create the view inside the <code>ListView</code>:</p>
  <pre><code>struct ListView: View {
      let animals = [&quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;, &quot;&quot;]
  
      var body: some View {
          List {
              ForEach(animals, id: \.self) { animal in
                  NavigationLink(
                      destination: DetailView(viewModel: DetailViewModel(text: animal))
                  ) {
                      Text(animal)
                  }
              }
          }
      }
  }
  </code></pre>
  <p>where <code>DetailViewModel</code> here is simply defined as follows:</p>
  <pre><code>class DetailViewModel: ObservableObject {
      @Published var text: String
  }
  </code></pre>
  <p>(A view model is certainly over-engineered here, but it's just for the sake of explaining the problem.)</p>
  <h3>⚡️ The Problem</h3>
  <p>As the destination views for all navigations links are created each time the list view's <code>body</code> is updated, so are the respective view models. That's not much of a problem for a simple view model as shown above, but it certainly becomes a problem with more complex real-world view models. For example, a view model might instantiate other classes that are rather expensive to initialize. This would be done at the time of showing the <code>ListView</code> <strong>for each and every <code>DetailView</code> (model)</strong> – regardless of whether it's ever going to be shown (needed) or not.</p>
  <p>Thus, it seems to me like an anti-pattern to create view models inside the bodies of other views. Still, it is the most common practice I've seen in code examples and articles across the Internet.</p>
  <h3>❓ My Question</h3>
  <p>Is there a way to keep a <em>SwiftUI</em> view from instantiating the destinations views of <code>NavigationLink</code>s immediately? Or is there a way to create view models for view to be used as navigation link destinations outside of a view's <code>body</code>?</p>