@EnvironmentObject

When we use the @EnvironmentObject property wrapper, we can use our object across multiple SwiftUI views without having to use an @ObservedObject every time our object is passed to other views. We can only apply the wrapper to classes that conform to the ObservableObject protocol.

Here’s a small example:

This will allow us to use our data throughout the app. We first need to pass our property to the ContentView using the modifierenvironmentObject(_:). This will give all Child Views of the ContentView access to the Environment Object.

In our ContentView, we call the ListCars view. In this view, we define an @EnvironmentObject property. When we use @EnvironmentObject, we say that the values come from SwiftUI’s environment, without having to create them in the view. The example shown would now work without using the @StateObject or @ObservedObject property wrapper.

Without the @EnvironmentObject Wrapper, we would have to pass our data to every View. Let’s say we have Views from A to F and F wants data that View A has, then every View would need an @ObservedObject to pass the data to the Views until it finally reaches View F. It doesn’t matter if the individual Views need the object or not, they still have to pass it on.

@EnvironmentObject

Wenn wir den Property Wrapper @EnvironmentObject benutzen, können wir unser Objekt über mehrere SwiftUI Views hinweg benutzen, ohne jedes Mal ein @ObservedObject zu nutzen, dass unser Objekt an andere Views weitergibt. Wir können den Wrapper nur auf Klassen anwenden, die Konform zu dem ObservableObject Protocol sind.

Hierzu ein kleines Beispiel:

Damit wir unsere Daten über die ganze App benutzen können, müssen wir zunächst über den Modifier environmentObject(_:) unsere Property an die ContentView übergeben. Daraufhin haben alle Child Views der ContentView Zugriff auf das Environment Object.

In unserer ContentView rufen wir die ListCars View auf. In dieser View definieren wir eine @EnvironmentObject Property. Sobald wir @EnvironmentObject benutzen, sagen wir, dass die Werte von SwiftUI’s Environment kommen, ohne dass sie in der View erstellt werden müssen. Das gezeigte Beispiel würde jetzt funktionieren, ohne die @SateObject oder @ObservedObject Property Wrapper benutzt zu haben.


Ohne den @EnvironmentObject Wrapper müssten wir unsere Daten an jeder View übergeben. Angenommen wir haben Views von A nach F und F möchte Daten haben, die View A besitzt, so bräuchte jede View ein @ObservedObject, um so die Daten an die Views zu übergeben, bis sie letztendlich View F erreichen. Dabei ist es egal, ob die einzelnen View das Objekt brauchen oder nicht, weitergeben müssen sie es trotzdem.