1

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

burnsi
  • 6,194
  • 13
  • 17
  • 27
Amin
  • 99
  • 5

3 Answers3

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.

Paulw11
  • 108,386
  • 14
  • 159
  • 186
0

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.

andrewbuilder
  • 3,629
  • 2
  • 24
  • 46
0

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
}
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56