@Binding

The @Binding property wrapper is a way to create a two-way connection to a value managed by something else. Most probably it is a @State from a parent view — this is the most common way of using it.

In the above code, you can see my NotificationBadge component — picture it as a toaster displayed at the bottom of the screen for a few seconds when the user does some action.

The isShown Bool property is passed by binding. This means that when you create a NotificationBadge view you need to pass a Bool controlled by a @State . You can create a Binding from a State using $ . You could also create a binding manually (more on that later), or create a binding from a ObservableObject @Published property.

You can also mutate a binding value. For example, I could turn it to false from within my NotificationBadge component using isShow.value = false . This will mutate the State , so it updates both the NotificationBadge and the parent view state.

Here is an example on how to use NotificationBadge

When to use it?

The example above is a good one. Binding is often used to pass a value controlled and persisted by a parent view, and to invalidate your view when this value changes. It’s a good tool for TextField , Toggle , custom components, etc. You can propagate changes and create relationships in a complex view hierarchy by passing a @State as binding around, while ensuring that only one view persists its value.

Create a binding manually

You can also create a Binding<Value> yourself. Apple provides a very convenient init method to do so. The power of this feature is that you could trigger action and side effects when the value is set and read it from a storage of your choice. In my case, I use it mostly to bind to a value stored in my AppState redux store and dispatch the desired action when it’s set. Here’s an example of one of my context menus:

As you can see, I toggle the binding in my Button action, which will dispatch an action of my store, and update the binding value to the desired boolean value, which in the end will update my view. Clean and simple.