SwiftUI – Invert a boolean binding

What about creating a custom prefix operator?

prefix func ! (value: Binding<Bool>) -> Binding<Bool> {
    Binding<Bool>(
        get: { !value.wrappedValue },
        set: { value.wrappedValue = !$0 }
    )
}

Then you could run your code without any modification:

.sheet(isPresented: !$viewModel.MyProperty) 

If you don’t like operators you could create an extension on Binding type:

extension Binding where Value == Bool {
    var not: Binding<Value> {
        Binding<Value>(
            get: { !self.wrappedValue },
            set: { self.wrappedValue = !$0 }
        )
    }
}

and later do something like:

.sheet(isPresented: $viewModel.MyProperty.not)

or even experiment with a global not function:

func not(_ value: Binding<Bool>) -> Binding<Bool> {
    Binding<Bool>(
        get: { !value.wrappedValue },
        set: { value.wrappedValue = !$0 }
    )
}

and use it like that:

.sheet(isPresented: not($viewModel.MyProperty))

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)