SwiftUI environmentObject: Referring to member variable: just 'foo' vs. 'self.foo', either way compiles, but just `foo` doesn't run

I'm following the SwiftUI Tutorial: https://developer.apple.com/tutorials/swiftui/working-with-ui-controls

It has this:

struct CategoryHome: View {
    @EnvironmentObject private var userData: UserData
    var body: some View {
                                           //// here here
    LandmarkList().environmentObject(self.userData)) {
                Text("See All")

I thought userData and self.userData is the same thing here because there is only one variable userData and no other var named userData in the scope? But if I remove self., the app compile but doesn't run. It's as if LandmarkList() cannot find the environmentObject userData.

Is userData vs. self.userData not the same? Why not?


I think the confusion here is that @EnvironmentObject is an attribute to receive an object. If this is the top level declaration where you're using the object, then it should be a normal attribute.

struct CategoryHome: View {
  var userData: UserData

  var body: some View {

and then inside of LandmarkList:

struct LandmarkList: View {
  @EnvironmentObject var userData: UserData

LandmarkList does not need to be directly passed the UserData in its initializer as it will use SwiftUI to resolve it behind the scenes.

So, if userData is an environment object, you just need to pass it in your ContentView or SceneDelegate to a higher parent view. You also do not need to send it to the LandmarkList as it should automatically inherit it.

Xcode Beta 3 this was not working so the work around is manually attaching environmentObjedt() to each subsequent view. This is stated in the Tutorial... If not, the app would just crash...

The good news is Beta 4 this is working now.

But still, why was self. needed? Because nested closure?

Xcode 11 Beta 4 now show this error:

Reference to property 'currentPage' in closure requires explicit 'self.' to make capture semantics explicit

Terms of Service

Privacy Policy

Cookie Policy