# \`toggled\` or \`isFalse\` property/method on bool for use with KeyPath APIs

**URL:** <https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464>\
**Category:** Discussion\
**Created:** [August 24, 2021, 7:44pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464 "2021-08-24T19:44:28Z")\
**Posts on this page:** 20\
**Page:** 2

<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:** [August 25, 2021, 8:04pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/22 "2021-08-25T20:04:35Z")

</div>

This is a specialization of `map`, which should be added first. I think `map` is needed, but not `toggled`, which is a confusing name for the reason Avi described.

```swift
public extension KeyPath {
  func map<Transformed>(
    _ transform: @escaping (Value) -> Transformed
  ) -> (Root) -> Transformed {
    { transform($0[keyPath: self]) }
  }
}

```

```swift
XCTAssertEqual(
  [true, true].map((\.self).map(!)),
  [false, false]
)

```

* * *

The ability to convert to a closure without a transformation is also currently missing.

```swift
public extension KeyPath {
  /// Convert a `KeyPath` to a partially-applied get accessor.
  func callAsFunction() -> (Root) -> Value {
    { $0[keyPath: self] }
  }

  /// Convert a `KeyPath` to a get accessor.
  func callAsFunction(_ root: Root) -> () -> Value {
    { root[keyPath: self] }
  }
}

```

---

<div class="post-metadata">

**Author:** ![GreatApe](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/greatape/32/2640_2.png) [@GreatApe](https://forums.swift.org/u/GreatApe)\
**Post date:** [August 25, 2021, 10:03pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/23 "2021-08-25T22:03:03Z")

</div>

I don't favour `toggled` but the concept certainly makes sense. It doesn't mean `isToggled`, it works just like all other past tense names in Swift:

```
var x: Array = ...
x.reverse() // x has now been reversed, whatever it was before

let y: Array = ...
let z = y.reversed() // z is the reversed version of whatever y is

```

so `toggled` is completely analogous :

```
var x: Bool = ...
x.toggle() // x has now been toggled, it's the negative of whatever it was

let y: Array = ...
let z = y.toggled // z is the negative of whatever y is

```

---

<div class="post-metadata">

**Author:** ![GreatApe](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/greatape/32/2640_2.png) [@GreatApe](https://forums.swift.org/u/GreatApe)\
**Post date:** [August 25, 2021, 10:12pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/24 "2021-08-25T22:12:20Z")

</div>

```nohighlight
extension Bool {
    var not: Bool { !self }
}

// You can just do this:
extension KeyPath where Value == Bool {
    var not: KeyPath<Root, Bool> {
        appending(path: \.not)
    }
}

// But I propose this:
prefix func !<T>(keyPath: KeyPath<T, Bool>) -> KeyPath<T, Bool> {
    keyPath.not
}

struct My {
    var great: Bool
}

func ttt() {
    let f = \My.great
    let g = \My.great.not // Uses the extension on Bool
    let h = f.not // Uses the extension on KeyPath
    let i = !\My.great
}

```

---

<div class="post-metadata">

**Author:** ![toph42](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/toph42/32/7807_2.png) [@toph42](https://forums.swift.org/u/toph42)\
**Post date:** [August 25, 2021, 10:15pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/25 "2021-08-25T22:15:02Z")

</div>

> [@GreatApe](#):
>
> ```swift
> // But I propose this:
> prefix func !<T>(keyPath: KeyPath<T, Bool>) -> KeyPath<T, Bool> {
> keyPath.not
> }
> 
> ```

This is exactly what I expected to already work when I was trying to filter based on a `KeyPath` to a `Bool`.

---

<div class="post-metadata">

**Author:** ![1-877-547-7272](https://avatars.discourse-cdn.com/v4/letter/1/278dde/32.png) [@1-877-547-7272](https://forums.swift.org/u/1-877-547-7272)\
**Post date:** [August 26, 2021, 5:07am UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/26 "2021-08-26T05:07:28Z")

</div>

I think that a `Bool.toggled` property would be too similar to the existing `!` operator and could cause confusion with new users about which they should use.

Also, the primary motivation of key path expressions being usable as function types is to be able to refer to instance properties in a slightly more convenient way. Key path expressions are not meant to be a replacement for closure expressions. Additionally, I don’t think  
`string.filter(\.isWholeNumber.toggled)`  
offers any benefits in terms of clarity or conciseness over  
`string.filter { !$0.isWholeNumber }`  
to most Swift programmers — I doubt there are many who know about key paths but don’t know about the `!` operator. Even if you find the shorthand `$0` argument name confusing, you could name the argument something like `character`:  
`string.filter { character in !character.isWholeNumber }`

I don’t think we should add an `!` operator that’s only for key paths where the value type is `Bool` like @GreatApe is proposing. However, I am interested in adding support for operators in key path expressions and key path–based `@dynamicMemberLookup` types. There have been previous discussions on these forums about allowing instance methods to be referenced within key paths:

> [@Why can’t key paths refer to instance methods?](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315):
>
> In most parts of Swift, instance methods are treated like properties. However, if you try to reference an instance method using a key path, you get a compiler error. Why is this the case? I assume there is a reason, but I cannot find it. It would be extremely useful in all the same places that other key paths are. Note that I am not asking about calling instance methods inside a key path. I want to know why this works: let instance = 100 let method = instance.isMultiple method(10) // true met…

> [@Allow key paths to reference unapplied instance methods](https://forums.swift.org/t/allow-key-paths-to-reference-unapplied-instance-methods/35582):
>
> [Allow key paths to reference unapplied instance methods](https://github.com/pcantrell/swift-evolution/blob/method-keypaths/proposals/NNNN-method-keypaths.md) The [original key path proposal](https://github.com/apple/swift-evolution/blob/master/proposals/0161-key-paths.md) expressly limited key paths to be able to reference only properties and subscripts: \Person.name // KeyPath\<Person, String\> \Person.pets[0] // KeyPath\<Person, Pet\> This proposal adds the ability for key paths to reference instance methods, optionally specifying argument names: \Person.sing // KeyPath\<Person, () -\> Sound\> \Person.sing(melody:lyrics:) // KeyPat…

and I think that allowing unary operators in key paths like  
`string.filter(!\.isWholeNumber)`  
is something that should be considered as well. Core Team member @Joe_Groff has [stated](https://forums.swift.org/t/why-can-t-key-paths-refer-to-instance-methods/35315/11) that there’s no fundamental reason key paths can’t support instance methods, and I assume the same thing is true for operators since their implementations are similar. This syntax is intuitive, too:

> [@toph42](#):
>
> This is exactly what I expected to already work when I was trying to filter based on a `KeyPath` to a `Bool` .

---

<div class="post-metadata">

**Author:** ![GreatApe](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/greatape/32/2640_2.png) [@GreatApe](https://forums.swift.org/u/GreatApe)\
**Post date:** [August 26, 2021, 5:34am UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/27 "2021-08-26T05:34:42Z")

</div>

Hm, so in the end you support operators on keypaths?

---

<div class="post-metadata">

**Author:** ![1-877-547-7272](https://avatars.discourse-cdn.com/v4/letter/1/278dde/32.png) [@1-877-547-7272](https://forums.swift.org/u/1-877-547-7272)\
**Post date:** [August 26, 2021, 7:05am UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/28 "2021-08-26T07:05:24Z")

</div>

I think it’s worth looking into.

I don’t think it should be done by extending the `Bool` type and creating a new `!` operator that operates on the `KeyPath<_, Bool>` type like you’re proposing, however: instead, I’m proposing that the implementation for key paths be changed so that it supports unary operators and instance methods.

I’d like to see what other people think of my proposal, though.

---

<div class="post-metadata">

**Author:** ![GreatApe](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/greatape/32/2640_2.png) [@GreatApe](https://forums.swift.org/u/GreatApe)\
**Post date:** [August 26, 2021, 7:10am UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/29 "2021-08-26T07:10:51Z")

</div>

Aha. Yeah that would be nice. The KeyPath would forward all operations to the value it points to. Sort of like the way dynamicMemberLookup works for Bindings but when applying functions.

Negation is definitely my most common use case for that, but when the key  
path points to an array it would be nice to be able to bake in a `.filter` or `.map` into the keypath itself.

---

<div class="post-metadata">

**Author:** ![Nickolas\_Pohilets](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nickolas_pohilets/32/10659_2.png) [@Nickolas\_Pohilets](https://forums.swift.org/u/Nickolas_Pohilets)\
**Post date:** [August 26, 2021, 8:28am UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/30 "2021-08-26T08:28:43Z")

</div>

I think currently `KeyPath.map()` is not possible because of equality. It is similar to indexing key paths which capture the index and require index to be `Equatable` (maybe even `Hashable`). Similar here - this would require [Equality of functions](https://forums.swift.org/t/equality-of-functions/30295).

---

<div class="post-metadata">

**Author:** ![GreatApe](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/greatape/32/2640_2.png) [@GreatApe](https://forums.swift.org/u/GreatApe)\
**Post date:** [August 26, 2021, 10:05am UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/31 "2021-08-26T10:05:27Z")

</div>

Why does the function you map have to be equatable? How is it different from mapping an array?

---

<div class="post-metadata">

**Author:** ![Nickolas\_Pohilets](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/nickolas_pohilets/32/10659_2.png) [@Nickolas\_Pohilets](https://forums.swift.org/u/Nickolas_Pohilets)\
**Post date:** [August 26, 2021, 10:24am UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/32 "2021-08-26T10:24:18Z")

</div>

Ah, sorry, I misread the code as returning `KeyPath<Root, Transformed>`. If it’s just a `(Root) -> Transformed`, then equality is indeed not a requirement.

---

<div class="post-metadata">

**Author:** ![GreatApe](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/greatape/32/2640_2.png) [@GreatApe](https://forums.swift.org/u/GreatApe)\
**Post date:** [August 26, 2021, 12:11pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/33 "2021-08-26T12:11:18Z")

</div>

Ah, you mean if the function is baked into the keypath, and we want keypaths to be equatable then functions have to be as well. Sure that's true. But I would settle for something like `MappedKeyPath` which is not equatable but otherwise has the nice properties of `KeyPath`.

---

<div class="post-metadata">

**Author:** ![Ilias\_Karim](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ilias_karim/32/2339_2.png) [@Ilias\_Karim](https://forums.swift.org/u/Ilias_Karim)\
**Post date:** [August 26, 2021, 1:32pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/34 "2021-08-26T13:32:33Z")

</div>

> [@1-877-547-7272](#):
>
> Additionally, I don’t think  
> `string.filter(\.isWholeNumber.toggled)`  
> offers any benefits in terms of clarity or conciseness over  
> `string.filter { !$0.isWholeNumber }`

I agree with your points, especially about allowing unary operators in key paths, which is a good solution unless something else like Jessy's suggestion for map gets used, which is a brilliant path forward in it's own write.

What I'd like to highlight about the point you make about one syntax, the one I proposed, not offering much benefit over the existing one is that small syntactic differences add up in complex codebases. I don't presume that you lack any experience working in lengthy codebases that make extensive use of key paths. For that reasons you must understand the benefits of not using anonymous arguments where they are not necessary (as they introduce boilerplate, even if it's of the most innocuous kind), and not using curly braces where they are not necessary to use, especially as code bases are nearly always shared between programmers of various experience levels.

Using curly braces as a substitute for key paths where there is no justifiable reason for not using them considering the alternatives suggested in this thread impairs readability in particular because curly braces are used in if/guard/if-else as I mentioned at the outset. With key paths, let's say e.g. if you use a contains statement, as a writer you won't need to use both parentheses and curly braces in order to place your contains test in an if statement.

In short, fewer anonymous arguments and fewer curly braces wrapped in parentheses for the sake of can only help to improve readability, not to mention brevity, which would be a secondary concern over readability in most cases.

---

<div class="post-metadata">

**Author:** ![Ilias\_Karim](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ilias_karim/32/2339_2.png) [@Ilias\_Karim](https://forums.swift.org/u/Ilias_Karim)\
**Post date:** [August 26, 2021, 1:33pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/35 "2021-08-26T13:33:55Z")

</div>

> [@1-877-547-7272](#):
>
> I don’t think it should be done by extending the `Bool` type and creating a new `!` operator that operates on the `KeyPath<_, Bool>` type like you’re proposing, however: instead, I’m proposing that the implementation for key paths be changed so that it supports unary operators and instance methods.

I really appreciate a proposal that would not extend the Bool type to create a redundant property. If there's a way to leverage the existing ! operator, that would be absolutely fantastic.

---

<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:** [August 27, 2021, 11:21am UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/36 "2021-08-27T11:21:03Z")

</div>

This already compiles. (Based on my previous code above.)

```swift
XCTAssertEqual(
  [true, true].map(!\.self),
  [false, false]
)

```

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

```

If the language adds the feature for extending closures, so more operators can be chained, is that enough?

Personally, I don't understand what a `KeyPath` is, and I'm not sure anybody does. The structured documentation doesn't define what "key" or "path" are. Does it fundamentally have to look like something that `Mirror` can work with, or does it just exist because `{ $0… }` is ugly? 🤷

---

<div class="post-metadata">

**Author:** ![GreatApe](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/greatape/32/2640_2.png) [@GreatApe](https://forums.swift.org/u/GreatApe)\
**Post date:** [August 27, 2021, 12:18pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/37 "2021-08-27T12:18:54Z")

</div>

Sure, keypaths are definitely a mystery. But practically speaking, it's nice to be able to create something type safe using a clear and succinct syntax, with syntax completion, store it if you want, and apply it to an instance.

I don't care about Mirror, but it would be great if you could

1. Refer to the existing instance methods of a leaf property, not just it's properties
2. Apply external functions to the leaf property

and still have a KeyPath, or at least a subtype of that.

---

<div class="post-metadata">

**Author:** ![Saklad5](https://avatars.discourse-cdn.com/v4/letter/s/4491bb/32.png) [@Saklad5](https://forums.swift.org/u/Saklad5)\
**Post date:** [August 27, 2021, 10:20pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/38 "2021-08-27T22:20:57Z")

</div>

> [@anon9791410](#):
>
> Personally, I don't understand what a `KeyPath` is, and I'm not sure anybody does. The structured documentation doesn't define what "key" or "path" are. Does it fundamentally have to look like something that `Mirror` can work with, or does it just exist because `{ $0… }` is ugly?

Key paths are references to properties. They are usually not useful, but _extremely_ useful when they are. They may be used to produce extremely powerful APIs, and allow consumers a level of flexibility normally associated with runtime manipulation.

While I do not actually know for sure, I consider it probable that compile-time optimization is easier for more constrained parameters like key paths than for closures, which have to have their own scope and everything. It is certainly easier to reason about when reading code.

Personally, I think every declaration in Swift should be accessible via key path, unless there is a compelling reason they should not be. Operators are glorified functions, and they should be treated as such when it comes to key paths. Same with subscript methods, which would be _really_ nice for drilling down into dictionaries via key path.

---

<div class="post-metadata">

**Author:** ![jpmhouston](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jpmhouston/32/4045_2.png) [@jpmhouston](https://forums.swift.org/u/jpmhouston)\
**Post date:** [August 28, 2021, 10:04am UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/39 "2021-08-28T10:04:03Z")

</div>

A modest alternate proposal: properties of type bool or functions returning bool automatically get a negation generated whenever Swift can infer a suitable name.

So `var isXxx: bool` implicitly also defines a `var isNotXxx: bool` with the obvious implementation, such as `isNotWholeNumber` or `isNotHidden`.

And same for `func isXxx(...)` will implicitly also define `func isNotXxx(...)`, such as `isNotDetailLink(...)`.

There could be a small set of these well-defined inference rules, "doesXxx" infers "doesNotXxx", "shouldXxx" infers "shouldNotXxx", "canXxx" infers "cannotXxx", "willXxx" infers "wontXxx".

But these rules doesn't work ideally in many cases: the above example `isNotHidden` could arguably instead be `isShown`, `isNotEven` would clearly be better named `isOdd`. And of course there are many bool functions and properties are not spelled like "isXxx" at all, like `contains(...)` whose negation should maybe be `omits(...)`. For these an attribute `@negation(name: isOdd)` can correct an inferred negation or provide one when none can be inferred. And for the few cases where a property or function shouldn't get any negation when the rules normally would infer one, then they can be annotated with `@negation(none)`.

I'm maybe 3/4's kidding.

But maybe even without dubious language support, we could foster the practice of defining negation properties and functions manually. Who knows one day they could be regarded as "Swifty". Or could possibly a `@negation` attribute on its own be a good idea after all without the flaky inference part?

---

<div class="post-metadata">

**Author:** ![danhalliday](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/danhalliday/32/18264_2.png) [@danhalliday](https://forums.swift.org/u/danhalliday)\
**Post date:** [August 29, 2021, 7:27pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/40 "2021-08-29T19:27:57Z")

</div>

Maybe (surely?) this has come up in previous discussion, but the obvious solution having spent time with Ruby is to throw a `reject` function into your project, which is the opposite of `filter`. I understand that kind of thing is never going to make it into the standard library though.

---

<div class="post-metadata">

**Author:** ![Ilias\_Karim](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/ilias_karim/32/2339_2.png) [@Ilias\_Karim](https://forums.swift.org/u/Ilias_Karim)\
**Post date:** [September 1, 2021, 2:23pm UTC](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464/41 "2021-09-01T14:23:14Z")

</div>

> [@danhalliday](#):
>
> Maybe (surely?) this has come up in previous discussion, but the obvious solution having spent time with Ruby is to throw a `reject` function into your project, which is the opposite of `filter` . I understand that kind of thing is never going to make it into the standard library though.

We'll never know until it's proposed. I give it a strong +1.

[Previous page](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464.md?page=1)

[Next page](https://forums.swift.org/t/toggled-or-isfalse-property-method-on-bool-for-use-with-keypath-apis/51464.md?page=3)
