# \[Pitch\] Add KeyPaths Boolean custom operators

**URL:** <https://forums.swift.org/t/pitch-add-keypaths-boolean-custom-operators/62626>\
**Category:** Pitches\
**Tags:** keypaths, swift\
**Created:** [January 18, 2023, 11:09am UTC](https://forums.swift.org/t/pitch-add-keypaths-boolean-custom-operators/62626 "2023-01-18T11:09:06Z")\
**Posts on this page:** 1\
**Showing post:** 4

<div class="post-metadata">

**Author:** ![anon9791410](https://avatars.discourse-cdn.com/v4/letter/a/9fc348/32.png) [@anon9791410](https://forums.swift.org/u/anon9791410)\
**Post date:** [January 19, 2023, 5:59am UTC](https://forums.swift.org/t/pitch-add-keypaths-boolean-custom-operators/62626/4 "2023-01-19T05:59:59Z")

</div>

While what you're talking about should be part of the standard library, negation is too common to not be in the standard library too. Just like [`toggle()`](https://developer.apple.com/documentation/swift/bool/toggle()), the lack of it won't last. Everybody needs it, all the time.

(`toggled`, as shown above, is not an accurate name for this, however—"toggled" means you flip the thing via mutation first and then return the flipped value. [That doesn't work with key paths](https://forums.swift.org/t/key-path-cannot-refer-to-which-has-a-mutating-getter/28856/7).)

```swift
public extension Bool {
  /// Toggle, and return the new value.
  var toggled: Self {
    mutating get {
      toggle()
      return self
    }
  }
}

```

[I don't think the other ones add anything.](https://knowyourmeme.com/memes/theyre-the-same-picture)

```swift
(\.value == false)
{ $0.value == false }

```

The general form works for key path expressions:

```swift
infix operator …

public func … <Root, Value, Transformed>(
  value: @escaping (Root) -> Value,
  transform: @escaping (Value) -> Transformed
) -> (Root) -> Transformed {
  { transform(value($0)) }
}

public prefix func !<Root>(
  getBool: @escaping (Root) -> Bool
) -> (Root) -> Bool {
  getBool…(!)
}

```

But you also need the specialized form to deal with key paths when they're variables:

```swift
public extension KeyPath {
  /// - Returns: A closure that returns a transformed `Value`.
  func map<Transformed>(
    _ transform: @escaping (Value) -> Transformed
  ) -> (Root) -> Transformed {
    { transform($0[keyPath: self]) }
  }
}

public extension KeyPath where Value == Bool {
  static prefix func !(keypath: KeyPath) -> (Root) -> Value {
    keypath.map(!)
  }
}

```

---

_[View the full topic](https://forums.swift.org/t/pitch-add-keypaths-boolean-custom-operators/62626)._
