Is this usage a @State variable wrong?

Hi,

the documentation for @State says:

You should only access a state property from inside the view’s body, or from methods called by it.

Therefore I am wondering of this is an incorrect (as aValue is set/accessed outside of a "view's body") usage of @State which, while it works now, might break in the future:

Code Block swift
@main
struct SwiftUIArrayUpdateTestApp: App {
@State private var aValue = 5
var body: some Scene {
WindowGroup {
ContentView(value: $aValue)
}
}
}



Why do you set the var as private ?

Try removing the private keyword.
@Claude31

The coding works just fine. My question was, if either the coding is not correct (while working fine) or the documentation is probably not correct (or at least unclear).

As for your question regarding my usage of private. Here's the whole paragraph from the documentation (emphasis added).

You should only access a state property from inside the view’s body, or from methods called by it. For this reason, declare your state properties as private, to prevent clients of your view from accessing them. It is safe to mutate state properties from any thread.

Cheers.





while it works now, might break in the future

Simply saying, it is not clearly documented.

The description you have referred may have been written when SwiftUI does not have App, and is intended to clarify the context where @State is only used in Views.

You may want to get some responses from Apple's engineer, but as far as I can see, engineers of SwiftUI are not so active as found in some other topics.
You can send a feedback about documentation of this issue using Apples Feedback Assistant.
@milutz I saw the doc, but does it work if you remove the private keyword ?
@Claude31 it works with or without the private keyword. My initial question was regarding the correctness of the documentation. I am accessing a @State property outside of a view's body, whereas the documentation states:

only access a state property from inside the view’s body

Cheers, Michael


Is this usage a @State variable wrong?
 
 
Q