Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: How to use `!` operator before `$` bindable object operator?

I'm unable to use logical not ! operator with Bindable $ object.

Here is the scenario I want-

struct ContentView: View {
@State private var isLoggedIn:Bool = true
var body: some View {

    Text("Root View")
        .sheet(isPresented: !self.$isLoggedIn) {
            SignInView()
        }
        .onAppear { self.performAuthentication() }
   }
}

Sign In View should present as soon as I set isLoggedIn = false by some button action. For which I have to use logical not operator before $.

Compiler error: Cannot convert value of type 'Binding' to expected argument type 'Bool'

How can I achieve this?

like image 692
Master AgentX Avatar asked Sep 14 '25 00:09

Master AgentX


1 Answers

As I said in comment to question there were approach posted for SwiftUI: transform Binding into another Binding. If you, however, want to have it explicitly as operator, you can use the following (tested & works with Xcode 11.2)

extension Binding where Value == Bool {
    static prefix func !(_ lhs: Binding<Bool>) -> Binding<Bool> {
        return Binding<Bool>(get:{ !lhs.wrappedValue }, 
                             set: { lhs.wrappedValue = !$0})
    }
}
like image 155
Asperi Avatar answered Sep 16 '25 15:09

Asperi