Get value of a Binding

Viewed 2533

I am trying to create @State variable inside a custom initialiser based on a binding that is passed in. I am getting error Cannot convert value of type 'Binding<Color>' to expected argument type 'Color'. Is there a way to extract raw value of the biding itself? This is an example:

struct ContentView: View {
    
    @State var color = Color.red
    
    var body: some View {
        
        SomeView(color: $color)
    }
}

struct SomeView: View {
    
    @Binding var color: Color
    @State var someOtherColor: Color
    
    init(color: Binding<Color>) {
        
        _color = color
        
        _someOtherColor = State(initialValue: color) // ERROR: Cannot convert value of type 'Binding<Color>' to expected argument type 'Color'
    }
    
    var body: some View {
        Text("Hello, world!")
    }
}
1 Answers

You can use the wrappedValue property of Binding to access its underlying value.

_someOtherColor = State(initialValue: color.wrappedValue)
Related