Binding Constant Alternative, but Mutable

Viewed 175

I have a view like this:

struct View1: View {
    @Binding var myVariable: Bool
    
    init() {
        _myVariable = Binding.constant(true) // It works but myVariable is immutable, so I can't edit myVariable
    }
    
    init(myVariable: Binding<Bool>) {
        _myVariable = myVariable
    }
    
    var body: some View {
        Button("Change") {
            myVariable.toggle()
        }
    }
}

struct View2: View {
    var body: some View {
        View1()
    }
}

struct View3: View {
    @State var myVariable = false

    var body: some View {
        View1(myVariable: $myVariable)
    }
}

And I want to make this: If there is a parameter provided, set this to myVariable like second init in View1. Else, set the first value of myVariable like in first init.

I tried to use Binding.constant(value) but it is immutable. And I can't edit the variable. So, I need a mutable Binding initializer like Binding.constant(value). But I can't find it.

How can I solve this problem?

1 Answers

To avoid over-complicating View1, you can create an intermediate view with that name, and then have a private 'internal' view which has the actual implementation.

Code:

private struct View1Internal: View {
    @Binding var myVariable: Bool

    var body: some View {
        Button("Change") {
            myVariable.toggle()
        }
    }
}
struct View1: View {
    private enum Kind {
        case state
        case binding(Binding<Bool>)
    }

    @State private var state = true
    private let kind: Kind

    init() {
        kind = .state
    }

    init(myVariable: Binding<Bool>) {
        kind = .binding(myVariable)
    }

    var body: some View {
        switch kind {
        case .state: View1Internal(myVariable: $state)
        case .binding(let binding): View1Internal(myVariable: binding)
        }
    }
}
Related