Hi! I have a stateful object that should be created in my app entry point and delivered through my component graph:
@main
@MainActor struct MyApp : App {
@State private var myAppState = MyAppState()
var body: some Scene {
...
}
}
The MyApp
is a struct value type… in a SwiftUI world that seems to imply it could "go away" and be recreated as the system sees appropriate. We see this with view components all the time (hence the State
wrapper to help preserve our instance across the lifecycle of our identity)… but I'm wondering if this State
wrapper is even necessary with an App
entry point. Could this struct ever go away? Would there be any legit reasons that this struct should go away and recreate over one SwiftUI app lifecycle (other than terminating the app and starting a whole new process of course)?
And what lifecycle is the SwiftUI.State
tied to in this example? In a view component our SwiftUI.State
is tied to our component identity. In this example… we are tied to app component identity? Is there ever going to be multiple legit app component identities live in the same process?
I'm thinking I could just go ahead and keep using State
as a best practice… but is this just overkill or is there a real best practice lurking under here? Any more ideas about that? Thanks!
State property wrapper manages transient properties. If the view doesn’t modify the data then you should declare it as a standard Swift property.
If you value is transient and changes, you would want to use the state propriety because when the value changes, SwiftUI updates the parts of the view hierarchy that depend on the value.
Don’t use state properties for persistent storage because the life cycle of state variables mirrors the view life cycle.
If you want to learn more about how to model your data and manage your interface state does please see these resources: