Implementation:
extension Bool {
var toggled: Bool {
!self
}
}
Usage:
let trueBool = true
print(trueBool.toggled) // false
Rationale:
toggled
provides ease-of-use in functional contexts.
E.g.
In the status quo, one way to filter whole numbers from a string would be as follows.
let string = "abc12345"
let nonDigits = string.filter { !$0.isWholeNumber } // "abc"
However, such an approach does not leverage the benefit key paths introduced in Swift 5.
You can see these in use in the following expressions.
let string = "abc12345"
let nonDigits = string.filter(\.isWholeNumber.toggled) // "abc"
Besides brevity, a major advantage is that when used in an if-let or guard-let clause, the filter expression will not need to be wrapped in both parentheses as well as curly braces.
Prior art:
Other Swift types offer similar interfaces that can be drawn on for inspiration. Take the Sequence for instance.
It offers two methods, one which mutates, reverse()
and another reversed()
which does not.
var collection = ["A", "B", "C"]
print(collection.reverse())
// ["C", "B", "A"]
print(collection)
// ["C", "B", "A"]
let collection = ["A", "B", "C"]
let reversedCollection = collection.reversed()
print(collection)
// ["A", "B", "C"]
print(Array(reversedCollection))
// ["C", "B", "A"]
The prior art would imply a corresponding set of methods on the Bool type.
.toggle()
already exists on Bool.
var bool = true
bool.toggle()
print(bool)
// false
That makes it plain the obvious omission of.toggled
on Bool, that would clean up a lot of filtering code.
This approach provides greater utility to developers to the swift ecosystem, who would either
- declare toggled/toggled() in each code base worked on
- use curly braces simply in order to access the '!" not operator.
- as mentioned at the outset of my post, not having to wrap curly braces in parentheses in the context of if-let and guard-let statements where the only reason to do so would be to access with "!" not operator.
The resulting benefits include: - code deduplication through declaring such a property in Swift standard library
Previous thread: [Proposal] Add property for negation to Bool - Evolution / Discussion - Swift Forums