Search code examples
swiftswiftuiproperty-wrapper

@State autogenerated underscore-prefixed member variable


I noticed via an Xcode autocompletion suggestion that @State seems to not only autogenerate a $-prefixed member for accessing the corresponding Binding (as is commonly known), but also a _-prefixed member, seemingly exposing the actual State wrapper.

This makes me wonder, what's the use case for it, and where is it mentioned in the docs?

enter image description here


Solution

  • I found out it's actually due to how Swift (rather than SwiftUI) compiles propertyWrappers under the hood.

    From the official swift docs (under propertyWrapper):

    The compiler synthesizes storage for the instance of the wrapper type by prefixing the name of the wrapped property with an underscore (_)—for example, the wrapper for someProperty is stored as _someProperty. The synthesized storage for the wrapper has an access control level of private.

    Here's what's happening each time you use a propertyWrapper:

    enter image description here (From better programming)

    As to its practical application in the context of SwiftUI, you can use it to initialize the @State variable, as described in this SO answer or this blog post.