title: SwiftUI best practices: should View have a constant to singletons and should they be passed in the Environment?
body: <p>In Xcode 12 template for a SwiftUI project using Core Data, Apple provides the following code:</p>
  <pre><code>import SwiftUI
  
  @main
  struct CoreDataApp: App {
      let persistenceController = PersistenceController.shared
  
      var body: some Scene {
          WindowGroup {
              ContentView()
                  .environment(\.managedObjectContext, persistenceController.container.viewContext)
          }
      }
  }
  </code></pre>
  <p>In this case, the persistenceController is a singleton.</p>
  <p>What's the difference with following code, where the singleton is initialized and passed at the same time? Why do we use a constant for the singleton?</p>
  <pre><code>import SwiftUI
  
  @main
  struct CoreDataApp: App {
  
      var body: some Scene {
          WindowGroup {
              ContentView()
                  .environment(\.managedObjectContext, PersistenceController.shared.container.viewContext)
          }
      }
  }
  </code></pre>
  <p>Also, are there any advantages to providing this singleton to the environment? Couldn't we just use <code>PersistenceController.shared.container.viewContext</code> directly in subviews?</p>
  <p>I'm asking because I have few services singletons in my app but I don't want to initialize them from the main <code>App</code> but in subviews.</p>