Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Invert a boolean binding

Tags:

ios

swift

swiftui

I have a binding in a swiftUI view. Something along the lines of :

struct MyCoolView: View {      @ObservedObject var viewModel: ViewModel      var body: some View {          Text("Here is a cool Text!").sheet(isPresented: $viewModel.MyProperty) {                              SomeModalView()}         } }  

I want the isPresented to use the opposite boolean value of what is stored in the property.

Swift wont let me just do something like

.sheet(isPresented: !$viewModel.MyProperty)  

(It gives me an error about cannot convert Binding <Bool> to Bool)

Any thoughts on how to deal with this?

like image 539
snarik Avatar asked Dec 24 '19 23:12

snarik


2 Answers

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)) 
like image 159
tgebarowski Avatar answered Sep 22 '22 03:09

tgebarowski


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()} }  
like image 40
E.Coms Avatar answered Sep 24 '22 03:09

E.Coms