skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. Try like below:-

    struct ContentView: View {
        
        var body: some View {
            LightPairing(light: .constant(nil))
        }
    }
    struct LightPairing: View {
        @Binding var light: Color?
        init(light: Binding<Color?>) {
            self._light = light
        }
        var body: some View {
            ZStack {
                //Some Code
            }
        }
        // the rest of the code, such as body is omitted since it is very long
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search