Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between SwiftUI State initializers

Tags:

swift

swiftui

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?

like image 595
iComputerfreak Avatar asked Oct 20 '19 14:10

iComputerfreak


People also ask

What does state mean in SwiftUI?

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.

What is state and binding in SwiftUI?

@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.

What is a state property Swift?

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.

What is an initializer 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.


1 Answers

According to the swift-evolution proposal:

init(initialValue:) has been renamed to init(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:).

like image 169
iComputerfreak Avatar answered Oct 07 '22 17:10

iComputerfreak