I have a question about optional bindings in swiftUI. I have a struct:
struct LightPairing: View {
@Binding var light: Color?
init(light: Binding<Color?>) {
self._light = light
}
// the rest of the code, such as body is omitted since it is very long
}
I want to give the light property a default value of nil, light: Binding<Color?> = nil, but it does not work. Is there anyway to get around this issue?
Edit: When I do:
light: Binding<Color?> = nil
I get the error message saying
"Nil default argument value cannot be converted to type
Binding<Color?>"
3
Answers
A
@Binding
takes a value from another property, such as a@State
property wrapper (a property that owns the value).You can either set the
@Binding
from a property in another struct (elsewhere)…then call…
or alternatively change your
@Binding
to a State property in this struct.Where this occurs will depend on your app logic.
Your property is of type
Binding<Color?>
so you can’t simply assignnil
. You have to assignBinding<Color?>
where the bound value isnil
.You can do this via
Binding.constant()
:Now, if you don’t provide a binding for
light
a default value will be supplied for you.Try like below:-