'SwiftUI Binding default value (Argument labels '(wrappedValue:)' do not match any available overloads)

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?



Solution 1:[1]

Here it is

struct MyView: View {
    @Binding var a: Bool
    init(a: Binding<Bool> = .constant(true)) {
        _a = a
    }

    var body: some View {
        Text("MyView")
    }
}

backup

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1