Search code examples
swiftswiftuidata-bindingobservableswift-property-wrapper

SwiftUI – @State vs @Binding


I am learning iOS Programming with Swift and SwiftUI. I know very little and I am very confused about the difference between a @State and a @Binding.

If I understood it correctly, @Binding is just technically @State but it doesn't update the view. If that is the case then why would I need @Binding if I could just use @State to do the same thing?


Solution

  • SwiftUI is a declarative Component-Oriented framework. You have to forget about MVC where you have controllers mediating between view and model. SwiftUI uses diffing algorithm to understand changes and update only corresponding views.

    @State

    • A State property is connected to the view. A State property is permanently being read by the view. That means that every time the @State property gets changed/updated, the view gets re-rendered and eventually displays the content depending on the @State's data.
    • State is accessible only to a particular view.
    • Simple properties like strings, integers and booleans belongs to a single view - mark as private.
    • All the fields marked as State are stored in special separated memory, where only corresponded view can access and update them.

    @Binding

    • BindableObject protocol, which requires a didChange property. It makes possible to use it inside Environment and rebuild view as soon as it changes.
    • The didChange property should be a Publisher, which is a part of a new Apple’s Reactive framework called Combine.
    • The main goal of Publisher is to notify all subscribers when something changes. As soon as new values appear, SwiftUI will rebuild Views.

    @EnvironmentObject

    • It is a part of feature called Environment. You can populate your Environment with all needed service classes and then access them from any view inside that Environment.
    • @EnvironmentObject is accessible for every view inside the Environment.
    • @EnvironmentObject Properties created elsewhere such as shared data. App crashes if it is missing.
    • The Environment is the right way of Dependency Injection with SwiftUI.