Property Wrapper In Swiftui
Helping while passing data in between views
They are 3 property wrapper in swiftui, which so helpful to developer.
- State
- Binding
- Environment Object
In this blog we will see about State and Binding
State in swiftui
swiftui fully play with Struct
, thats great but sad part is like variables in struct are immutable. To overcome it, we have many ways and @State
is one of the best way to do.
Basically @State
helps to make the immutable variables into mutating variables.
So now i can change the var a
value anywhere and it will also change.
Other best part of @State and Struct
is, if im using var a
anywhere in UI part and changing it. Struct will automatically send a notification to swiftui and that ui part will updated.
Additional information
When we declare a variable with @state
, memory of that variable will be saved separately (Example like a global)
Binding in swiftui
Imagine
We have two views called view1
and view2
. sending data from view1
to view2
and changing that data value in view2
and now we wanted that changed data to affect in view1
UI too as soon as data have been change.
So we need read and writing at same . don't worry this stuff all will be handled my swiftui Binding itself. Just we need to do is bind
the state
value and send from view1
to view2
thats it.
Example
So in view we have state variable and just displaying in a text
and binding that state variable with view2 and passing to view2
In view2
we declared a variable with Binding. So whenever we changing that variable in view2
, view1
variable will also affected and update in UI.
This is small stuffs about Property Wrapper in swiftui. Keep this untill we meet again.
If any mistake or you need to shout me, comments session in always opened
Nanri vanakkam 🙏