Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 993
Linus Avatar asked Mar 28 '20 11:03

Linus


1 Answers

Here it is

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

    var body: some View {
        Text("MyView")
    }
}
like image 93
Asperi Avatar answered Sep 28 '22 20:09

Asperi