When initializing an @State
variable, there are two initializers:
/// Initialize with the provided initial value.
public init(wrappedValue value: Value)
/// Initialize with the provided initial value.
public init(initialValue value: Value)
Is there a difference between the two initializers or are they doing the same?
Is one of them preferred to use when creating a new @State
variable?
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.
@State property wrappers are used to read and write variables from a structure. It is used in single view and is recommended that you set its property as private so that other views cannot access it. @Binding property wrappers are used to access variables from other views.
SwiftUI uses the @State property wrapper to allow us to modify values inside a struct, which would normally not be allowed because structs are value types. When we put @State before a property, we effectively move its storage out from our struct and into shared storage managed by SwiftUI.
An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer.
According to the swift-evolution proposal:
init(initialValue:)
has been renamed toinit(wrappedValue:)
to match the name of the property.
As of Swift 5.1 both are available and none is marked as deprecated. I still would recommend using init(wrappedValue:)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With