I have a view that internally manages a @State variable that keeps track of the current index. So something like:
struct ReusableView: View {
@State var index: Int = 0
var body: some View {
Text("The index is \(self.index)"
// A button that changes the index
}
}
This view is going to be reused throughout the app. Sometimes the parent view will need access to the index, so I refactored it like this:
struct ParentView: View {
@State var index: Int = 0
var body: some View {
ReusableView($index)
}
}
struct ReusableView: View {
@Binding var index: Int
var body: some View {
Text("The index is \(self.index)"
// A button that changes the index
}
}
The problem
I don't want to enforce the parent view to always keep the state of the index. In other words, I want to optionally allow the parent view to be in charge of the state variable, but default to the Reusable View to maintain the state in case the parent view doesn't care about the index.
Attempt
I tried somehow to initialize the binding on the reusable view in case the parent view doesn't provide a binding:
struct ReusableView: View {
@Binding var index: Int
init(_ index: Binding<Int>? = nil) {
if index != nil {
self._index = index
} else {
// TODO: Parent didn't provide a binding, init myself.
// ?
}
}
var body: some View {
Text("The index is \(self.index)"
// A button that changes the index
}
}
Thank you!