How to initialise a @Binding

I have a hierarchy of views. The top level view has an @Binding property. I am wondering what is the best practice when it comes ot providing the intial value for this Binding?


The original value ( Or source of truth) should be in some model I guess. But I am not sure where the original value should be created and how this should be passed onto the view. Suppose we have a model object that 'owns' this value. The model object should provide the inital value for this. But how do you create an inital value for an @Binding variable? You could use .constant(Value) but that seem to create an immutable value. How do you create a mutable @Binding with an intial value?

Answered by coffeecoder in 374958022

I found the answer after watching the WWDC talk on "DataFlow through swiftUI". @Binding is used to pass "read/write" data from one view to the other. @Binding can never be 'The source of truth'. It is just a reference to a 'source of truth' that already exists.


'Source of truth' is the original data that the view refers to (. To create a 'source of truth' with read-only acces you can use plain swift properties in the view struct. (Or use @Environment). If you need read/write access you have two options


1) @State. You can use this option when the data you are using is completely local to the view (Such as your scroll position) which has no meening in your model


2) BindableObject. Use this when you have data in your model that the view needs to read and write to.


So @Binding is only a bridge that connects existing sources of data such as @State or @ObjectBinding. It can also access other Bindings as well.

Accepted Answer

I found the answer after watching the WWDC talk on "DataFlow through swiftUI". @Binding is used to pass "read/write" data from one view to the other. @Binding can never be 'The source of truth'. It is just a reference to a 'source of truth' that already exists.


'Source of truth' is the original data that the view refers to (. To create a 'source of truth' with read-only acces you can use plain swift properties in the view struct. (Or use @Environment). If you need read/write access you have two options


1) @State. You can use this option when the data you are using is completely local to the view (Such as your scroll position) which has no meening in your model


2) BindableObject. Use this when you have data in your model that the view needs to read and write to.


So @Binding is only a bridge that connects existing sources of data such as @State or @ObjectBinding. It can also access other Bindings as well.

> 2) BindableObject. Use this when you have data in your model that the view needs to read and write to.


Note that BindableObject has been replaced by ObservableObject as of beta 5.

Oh That's interesting thanks for that!

How to initialise a @Binding
 
 
Q