I want to easily provide mutable bindings to my views for SwiftUI previews (so that the preview is interactive unlike when you pass a .constant(...) binding). I followed the BindingProvider approach which allows for one value at a time, like this:
#Preview {
BindingProvider(true) { binding in
SomeToggleView(toggleBinding: binding)
}
}
It would be nice to pass in multiple values to be bound, like this
#Preview {
BindingProvider(true, "text") { toggleBinding, textFieldBinding in
SomeToggleAndTextFieldView(toggleBinding: toggleBinding, textFieldBinding: textFieldBinding)
}
}
So far I've arrived at this code, but it's not compiling and just says "Command SwiftCompile failed with a nonzero exit code"
struct BindingProvider<each T, Content: View>: View {
@State private var state: (repeat State<each T>)
private var content: ((repeat Binding<each T>)) -> Content
init(_ initialState: repeat each T,
@ViewBuilder content: @escaping ((repeat Binding< each T>)) -> Content)
{
self.content = content
self._state = State(initialValue: (repeat State(initialValue: each initialState)))
}
var body: Content {
content((repeat (each state).projectedValue))
}
}
Maybe I'm doing something wrong or maybe this is just a compiler issue? Any help would be greatly appreciated!
Statecan work even when not used as a property wrapper. For example,var countState: State<Int> = .init(initialValue: 0)works fine in aView, but you have to access its value ascount.wrappedValueand itsBindingascount.projectedValue.var state: (repeat State<each T>)and found that SwiftUI doesn't see thoseStates, probably because they're wrapped inside a tuple.