SwiftUI - Invert a boolean binding
You can build a binding by yourself:
Text("Here is a cool Text!").sheet(isPresented:
Binding<Bool>(get: {return !self.viewModel.MyProperty},
set: { p in self.viewModel.MyProperty = p})
{ SomeModalView()} }
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))