0

So let's say I have a view like this:

struct MyView {
    @Binding var inEditMode: Bool
    ...
}

In some cases, I want this view to be able to swap in and out of edit mode, but in other cases, I only want it to be read-only.

Now I can avhieve this by creating a State var in the view containing this view that just never gets edited:

struct MyContainer {
    @State alwaysFalse: Bool = false

    var view: some View {
        MyView(inEditMode: $alwaysFalse)
    }
}

But it seems a little unnecessary to introduce a state var here. Is there any way to skip this and do something like this?

struct MyContainer {
    var view: some View {
        MyView(inEditMode: ConstBinding<Bool>(false))
    }
}

I think it would make the intent a bit clearer.

sak
  • 2,612
  • 24
  • 55
  • Keep in mind that a `Binding` is a two-way connection by definition. If `MyContainer ` doesn't need communication with `MyView` you can just remove the variable or use an immutable variable `var alwaysFalse: Bool = false`. Using `.constant` outside of `preview` doesn't really make a whole lot of sense because you are using unnecessary resources allocating "mocking" a 2-way connection where it isn't needed. – lorem ipsum Mar 05 '22 at 14:09
  • You can create Binding with no set `MyView(inEditMode: Binding { false } set: { _ in })` – Quang Hà Mar 08 '22 at 03:19

0 Answers0