From bc68893ce1f214133fdf134aae10bf196d3bbdb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cihat=20G=C3=BCnd=C3=BCz?= Date: Tue, 13 Oct 2026 13:11:05 +0200 Subject: [PATCH] Write the inverted value through a negated Bool binding The setter of `!binding` wrote the new value unchanged into the original binding, so toggling a control bound to `!$isOff` stored the opposite of what the user chose. --- .../HandySwiftUI/Extensions/BindingExt.swift | 2 +- Tests/HandySwiftUITests/BindingExtTests.swift | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 Tests/HandySwiftUITests/BindingExtTests.swift diff --git a/Sources/HandySwiftUI/Extensions/BindingExt.swift b/Sources/HandySwiftUI/Extensions/BindingExt.swift index d8287ea..f1f7857 100644 --- a/Sources/HandySwiftUI/Extensions/BindingExt.swift +++ b/Sources/HandySwiftUI/Extensions/BindingExt.swift @@ -17,7 +17,7 @@ import SwiftUI public prefix func ! (value: Binding) -> Binding { Binding( get: { !value.wrappedValue }, - set: { value.wrappedValue = $0 } + set: { value.wrappedValue = !$0 } ) } diff --git a/Tests/HandySwiftUITests/BindingExtTests.swift b/Tests/HandySwiftUITests/BindingExtTests.swift new file mode 100644 index 0000000..6ebaa94 --- /dev/null +++ b/Tests/HandySwiftUITests/BindingExtTests.swift @@ -0,0 +1,22 @@ +import SwiftUI +import Testing + +@testable import HandySwiftUI + +@MainActor +struct BindingExtTests { + @Test + func negatedBindingWritesTheInvertedValue() { + var stored = false + let binding = Binding(get: { stored }, set: { stored = $0 }) + let negated = !binding + + #expect(negated.wrappedValue == true) + + negated.wrappedValue = false + #expect(stored == true) + + negated.wrappedValue = true + #expect(stored == false) + } +}