Strange object construction behaviour

I stumbled across this behaviour, and have excised it from my code, but I would like to understand why it was happening.

The following code (with names changed to protect the innocent) was causing two instances of MyClass to be instantiated... why? It seems like the StateObject ought to be set to the newly instantiated wrappedValue, and then the global gObj optional set to refer to that object. Also, that appears not to be the case, and a second MyClass gets instantiated (demonstrated by a print or breakpoint in its init method).

Code Block
var gObj: MyClass?
@main
struct MyApp : App {
@StateObject(wrappedValue: MyClass()) public var obj : MyClass
init() {
gObj = self.obj
}
var body: some Scene {
WindowGroup {
ContentView(obj: self.obj)
}
}
}

First of all, SwiftUI apps should not depend on when or how many times init is called or body is evaluated for App and Views.
In SwiftUI, struct like App or View is just a template of actually shown objects, and very similar to Storyboard of UIKit or XAML of WPF. (Hope you know any of them.)

To control the initialization of class objects, you can use @StateObject, but please care about using it correctly.
And in cases you want some global var of class objects, environmentObject may be one option to work with, but many things depend on the details how you want to use it.
Code Block
@main
struct MyApp : App {
@StateObject public var obj = MyClass()
var body: some Scene {
WindowGroup {
ContentView(obj: self.obj)
}
}
}


Strange object construction behaviour
 
 
Q