@State 自动生成下划线前缀成员变量
@State autogenerated underscore-prefixed member variable
我通过 Xcode 自动完成建议注意到 @State
似乎不仅自动生成一个 $
前缀的成员来访问相应的 Binding
(众所周知),也是一个 _
前缀的成员,似乎暴露了实际的 State
包装器。
这让我想知道,它的用例是什么,文档中在哪里提到它?
我发现这实际上是由于 Swift(而不是 SwiftUI)如何在幕后编译 propertyWrapper
s。
来自 official swift docs(在 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.
以下是每次使用 propertyWrapper
时发生的情况:
(来自 better programming)
关于SwiftUI的实际应用,可以用它来初始化@State
变量,详见 or this blog post.
我通过 Xcode 自动完成建议注意到 @State
似乎不仅自动生成一个 $
前缀的成员来访问相应的 Binding
(众所周知),也是一个 _
前缀的成员,似乎暴露了实际的 State
包装器。
这让我想知道,它的用例是什么,文档中在哪里提到它?
我发现这实际上是由于 Swift(而不是 SwiftUI)如何在幕后编译 propertyWrapper
s。
来自 official swift docs(在 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.
以下是每次使用 propertyWrapper
时发生的情况:
关于SwiftUI的实际应用,可以用它来初始化@State
变量,详见