Swift and SwiftUI tutorials for Swift Developers

What is @State in SwiftUI

State management is a crucial aspect of app development that every developer must address. Let’s consider that we are developing an app that is a music player.

When the user taps on the Play button, it would have to transition to the Stop button. In this implementation we need a mechanism to track the state of the app, allowing you to determine when to alter the appearance of the button.

SwiftUI provides many features to handle state management. One such feature is the @State property wrapper. When you annotate a property with @State, SwiftUI automatically stores it within your app. Additionally, views that use this property are automatically notified of any changes to its value. As a result, when the state changes, SwiftUI recalculates the affected views and updates the appearance of the app accordingly.

In SwiftUI, views are structs and we use the @State property wrapper to modify their values. We use this property wrapper to take care of saving the state outside the struct (view) so we can draw the view without losing the state we had.

When we add @State we are making it so that if for some reason its value changes, the view is completely regenerated, that is, everything inside the body variable is redrawn.

@State is a property wrapper, used to manage and synchronize the state of the view across different components and should be used with simple structure types like String, Int and arrays and generally should not be shared with other views. If you want to share values ​​across views you will probably use @ObservedObject or @EnvironmentObject, both of which guarantee that all views will be updated when the data changes.

The recommendation, for @State properties, is to declare them as private to reinforce that they are local, as follows

@State private var playButton: Bool = false

Only access a @State property from within the body view or from functions called from body.

1 comment
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Article

How to create a button with gradient and shadow in SwiftUI

Next Article

What is @Binding in SwiftUI

Related Posts