@State in Swift/SwiftUI
Why and how do we use @State?
State in SwiftUI is a property wrapper that allow us to modify values inside a struct, which would normally not be allowed because structs are value types. As we mentioned in the previous article, Structs are immutable. According to Apple,
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, use its variable name, which returns thewrappedValue
property value.
When we put @State
before a property, we effectively move its storage out from our struct and into shared storage managed by SwiftUI. This means SwiftUI can destroy and recreate our struct whenever needed (and this can happen a lot!), without losing the state it was storing.
If you have previously read the article on Mutating Variables, you are already familiar with the examples and how we modified the example. If not kindly refer to the previous article.
Figure 1, is a representation of the struct we worked on Mutating article which we couldn’t just access with mutating prefix. Although, we can fix this little issue through @State. Unfortunately, adding the…