'SwiftUI: transform Binding into another Binding

Is there a way to e.g. logically negate Binding<Bool>? For example, I've a state variable

@State var isDone = true

which I pass as a biding into different sub views. Then I want to use it e.g. with isActive in NavigationLink, so that it shows only when not isDone:

NavigationLink(destination: ..., isActive: ! self.$isDone ) // <- `!` means `not done`

Of course, I can invert my logic with isDone -> isNotDone, but it would be unnatural in many contexts. So is there any simple way to make inverse of a bool binding?



Solution 1:[1]

If I correctly understood you need the following:

extension Binding where Value == Bool {
    public func negate() -> Binding<Bool> {
        return Binding<Bool>(get:{ !self.wrappedValue }, 
            set: { self.wrappedValue = !$0})
    }
}

struct TestInvertBinding: View {
    @State var isDone = true
    var body: some View {
        NavigationView {
            NavigationLink(destination: Text("Details"), 
                isActive: self.$isDone.negate()) {
                Text("Navigate")
            }
        }
    }
}

struct TestInvertBinding_Previews: PreviewProvider {
    static var previews: some View {
        TestInvertBinding()
    }
}

backup

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1