init()
Value
conforms to ExpressibleByNilLiteral
.
Value
がExpressibleByNilLiteral
に準拠する場合に利用可能です。
init(wrappedValue : Value)
init(initialValue : Value)
Availability 有効性
Technology
@frozen @propertyWrapper struct State<Value>
SwiftUI manages the storage of a property that you declare as state. When the value changes, SwiftUI updates the parts of the view hierarchy that depend on the value. Use state as the single source of truth for a given value stored in a view hierarchy.
A State
instance isn’t the value itself; it’s a means of reading and writing the value. To access a state’s underlying value, refer to it by its property name, which returns the wrapped
property value. For example, you can read and update the is
state property in a Play
view by referring to the property directly:
struct PlayButton: View {
private var isPlaying: Bool = false
var body: some View {
Button(isPlaying ? "Pause" : "Play") {
isPlaying.toggle()
}
}
}
If you pass a state property to a child view, SwiftUI updates the child any time the value changes in the parent, but the child can’t modify the value. To enable the child view to modify the stored value, pass a Binding
instead. You can get a binding to a state value by accessing the state’s projected
, which you get by prefixing the property name with a dollar sign ($
).
For example, you can remove the is
state from the play button in the example above, and instead make the button take a binding to the state:
struct PlayButton: View {
var isPlaying: Bool
var body: some View {
Button(isPlaying ? "Pause" : "Play") {
isPlaying.toggle()
}
}
}
Then you can define a player view that declares the state and creates a binding to the state using the dollar sign prefix:
struct PlayerView: View {
var episode: Episode
private var isPlaying: Bool = false
var body: some View {
VStack {
Text(episode.title)
.foregroundStyle(isPlaying ? .primary : .secondary)
PlayButton(isPlaying: $isPlaying) // Pass a binding.
}
}
}
Don’t initialize a state property of a view at the point in the view hierarchy where you instantiate the view, because this can conflict with the storage management that SwiftUI provides. To avoid this, always declare state as private, and place it in the highest view in the view hierarchy that needs access to the value. Then share the state with any child views that also need access, either directly for read-only access, or as a binding for read-write access.
You can safely mutate state properties from any thread.
init()
Value
conforms to ExpressibleByNilLiteral
.
Value
がExpressibleByNilLiteral
に準拠する場合に利用可能です。
init(wrappedValue : Value)
init(initialValue : Value)
var wrappedValue : Value
var projectedValue : Binding<Value>
struct Binding