4

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?

2
  • 2
    I answered on similar question before, please see here Commented Feb 5, 2020 at 14:33
  • 1
    it is worth to mention that '$' in not 'bindable object operator'. If you have @somePropertyWrapper var value:Value = ..., $ prefix operator gives you its projectedValue. You can get a binding from a State by accessing its binding property. You can also use the $ prefix operator with any property of a State to create a binding. Commented Feb 5, 2020 at 17:12

1 Answer 1

6

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})
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

redefining ! operator woks, but i don't think it is good idea. you are better to avoid such a solution ...
@user3441734 Why? It's a great idea (I like this even better than the earlier negate method).
@matt it works, for sure. but without seeing its definition, it could be little bit unclear, especially the set part. !someBool generally don't change the value. it was a nice discussion about someInt++ a year ago, and !someBindigToBool looks for me more "unpredictable"
@user3441734 That's a fair point! You're saying that the advantage of negate is that it can be clearer that it produces a new binding. In fact one might argue just the opposite of what I just said, and suggest that we call that method negativeBinding or similar to make absolutely clear what it does.
@matt .-) yes. let say ! operator is prefix operator which return negated value, but don't change original value. that is what i will expect ... even negativeBinding sounds strange, maybe bindingNegativeValue sounds better.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.