Home > Back-end >  Optional binding a color in swiftUI
Optional binding a color in swiftUI

Time:07-13

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?>"

CodePudding user response:

You are misunderstanding the types here.

@Binding var light: Color?

Does not give you an optional Binding that you could set nil. It is a Binding of an optional Color?. If you want to set Color to nil use:

light = nil

CodePudding user response:

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)…

@State private var lightElsewhere: Color? = nil

then call…

LightPairing(light: $lightElsewhere)

or alternatively change your @Binding to a State property in this struct.

@State private var light: Color? = nil

Where this occurs will depend on your app logic.

CodePudding user response:

Your property is of type Binding<Color?> so you can't simply assign nil. You have to assign Binding<Color?> where the bound value is nil.

You can do this via Binding.constant():

struct LightPairing: View {
    @Binding var light: Color?
    init(light: Binding<Color?> = .constant(nil)) {
        self._light = light
    }
    // the rest of the code, such as body is omitted since it is very long
}

Now, if you don't provide a binding for light a default value will be supplied for you.

  • Related