In Swift you can define default values on a struct that can be overwritten on initialization:
struct myStruct {
var a: Int = 1
}
var instance1 = myStruct() // instance1.a -> 1
var instance2 = myStruct(a: 10) // instance2.a -> 10
However when I try to apply this to Bindings in a SwiftUI view I get an error:
struct MyView: View {
@Binding var a: Bool = Binding.constant(true)
var body: some View {
Text("MyView")
}
}
Argument labels '(wrappedValue:)' do not match any available overloads
I want to create a view which by default uses a constant boolean value but that can be overwritten by a "real" Binding:
struct ContainerView: View {
@State var hasSet = false
var body: some View {
Group {
MyView(a: $hasSet)
MyView() // should be equivalent to MyView(a: .constant(true))
}
}
}
Is it possible to define such a default value for a Binding in SwiftUI?
Here it is
struct MyView: View {
@Binding var a: Bool
init(a: Binding<Bool> = .constant(true)) {
_a = a
}
var body: some View {
Text("MyView")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With