1

Inside SceneDelegate the context is passed via .environment(\.managedObjectContext, context) why cannot it be passed via View's property? What's the advantage of doing so?

So instead of doing below

let contentView = FlightsEnrouteView()
    .environment(\.managedObjectContext, context)

We can pass the context via the View's initializer

let contentView = FlightsEnrouteView(context: context)

so inside FlightsEnrouteView should be,

struct FlightsEnrouteView: View {
    var context: NSManagedObjectContext
}

Test it and it compiles

XY L
  • 25,431
  • 14
  • 84
  • 143

1 Answers1

2

why cannot it be passed via View's property? What's the advantage of doing so?

It can. Just it is used by other wrappers like @FetchRequest from environment, but nobody stops you to combine them, because context is an object of reference type, so you can pass its reference anyway you want.

So the following is absolutely valid:

let contentView = FlightsEnrouteView(context: context)
    .environment(\.managedObjectContext, context)

and

struct FlightsEnrouteView: View {
    @EnvironmentObject(\.managedObjectContext) var envContext
    var context: NSManagedObjectContext
}
Asperi
  • 228,894
  • 20
  • 464
  • 690