Different SwiftUI @ Properties Explained


  1. @State: This is used to create mutable state for a SwiftUI view. The view manages the storage for the state, and automatically updates the view when the state changes. @State properties should be used for simple properties that belong to a single view and need to trigger an update of the view’s body when they change.
  2. @Binding: This is used when a property should actually reflect the state of another @State variable from a parent view, and changes to the property need to be reflected in the parent’s state. It is a way of passing state data around between different views.
  3. @ObservedObject: This is used when your view needs to respond to changes in an external object that can be shared across multiple views or parts of your app. The external object should conform to the ObservableObject protocol, and any properties of that object marked with @Published will cause views to be updated when they change.
  4. @StateObject: This is similar to @ObservedObject but signals that the view is responsible for the creation and lifetime of the object. SwiftUI will ensure that a @StateObject is only initialized once across multiple view updates. It is used to create and manage objects that are shared across multiple views or parts of your app.
  5. @EnvironmentObject: This is used when your view needs to access a shared data object that has been provided to it through the SwiftUI environment. It’s a way to share data across the entire app or a part of the app, without having to pass the data from view to view.
  6. @Environment: This is used to access values that are implicitly provided by the system or are globally set for your app. For example, you can use @Environment to access information like the user’s locale, the size of the display, or a @Published property in an ancestor view.

Leave a Reply

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