data binding swift
//In this case we are referring to the property wrapper @Binding in SwiftUI
//We want to take this analogies for Bindings
//Imagine if I did not bind my coffee cup. If I say filled the new cup, only the new cup will fill and not the original cup
//If I did bind my coffee cup, if I filled the new cup, it will also fill the original cup.
//Thus, this is what the @Binding property is for (or rather the analogy)
//Please look more into pass by reference and value for more context
//An example
//In this case we make a struct called Child with two arguments, name and age
struct Child {
var name: String
var age: Int
}
//Next, we can create a variable that stores this struct
var children = Child(name: "Hannah", age: 3)
//Let's say I want to asssign another variable with this one
var newChildren = children
//And I change the name of the child in newChildren
newChildren.name = "Sandy"
//If we print these out, we get two different values
print(children) // -> prints Child(name: "Hannah", age: "3")
print(newChildren) // -> prints Child(name: "Sandy", age: "3")
//This is an example of passing via value, where we are simply copy pasting the value
//Now, take this sample SwiftUI App:
struct ContentView: View {
@State var number = 0
var body: some View {
VStack {
Text(number)
Button("INCREMENT ME") {
number += 1
}
NumberView()
}
}
}
struct NumberView: View {
@State var number = 0
var body: some View {
Text("Number in ContentView: \(number)")
}
}
//There are 2 views here, and each have their own number State vars.
//The button there is to increment the number State var in the ContentView.
//Let's say that we wanted to make both the number vars in the NumberView and the ContentView go up, this setup won't work
//Or rather, it will just increment the number var in the ContentView, and not the NumberView
//This would be the passing by value example
//Instead, we can replace the @State in the NumberView to a @Binding
@State var number = 0 -> @Binding var number: Int
//This makes it so that you can "give" an integer to the number var in NumberView.
//Before we go any further, if you copied the code, there should be a error on the NumberView() line
//Just replace
NumberView() -> NumberView(number: $number)
//So, what this binding does, is that it tells contentview "Hey hey! Feed me an integer!"
//Then, we give it a value, or rather, pass it a value.
//But instead of just copy pasting the value, we now are giving the same value.
//That means, the number in NumberView and the number in ContentView are the SAME NUMBER
//This would be an example of PASSING VIA REFERENCE
//Also, if you run this on xcode, the numberview number var updates when you press the button.
//*Very sorry for the really long explanation, since it's a little tough to explain @Bindings