@Environment example out of Apple's own SwiftUI comments fails to compile

This exact code appears in apple's comment in the SwiftUI module, but when I use it, it fails to compile with errors:
  • Enum 'Environment' cannot be used as an attribute

  • Type annotation missing in pattern

So is apple wrong about their own code or did we get an Xcode version that does not support this construct?

I tried @EnvironmentObject as well and it get different errors.

Code Block
@main
struct MyApp: App {
@Environment(\.scenePhase) private var scenePhase
var body: some Scene {
...

Apparently if you include a definition elsewhere called Environment then @Environment will not compile. Yet there is not compile error or warning at the definition site. Seems like a bug to me.

You can resolve this by prefacing Environment with SwiftUI.

So, where you have

@Environment(\.scenePhase)

you will now have

@SwiftUI.Environment(\.scenePhase)

Worked for me at least

Evidently it did not want me to format that for some reason.

The reason that you need to used the fully qualified namespace ie add @SwiftUI.Environment is that there is another object defined with that name.

If you click 'Jump to Defintion' in Xcode it will not work, but if you search your project for 'Environment' you will see where else it is defined. You can rename that version to avoid having to prefix all your @Environment calls with SwiftUI

@Environment example out of Apple's own SwiftUI comments fails to compile
 
 
Q