Skip to content

Commit 2688607

Browse files
chriseidhofairspeedswift
authored andcommitted
Bool toggle proposal (#782)
* Bool toggle proposal * Suggestions by @xwu * Feature name * Update and rename nnnn-bool-toggle.md to 0199-bool-toggle.md
1 parent 2dd7b99 commit 2688607

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

proposals/0199-bool-toggle.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# Adding `toggle` to `Bool`
2+
3+
* Proposal: [SE-0199](0199-bool-toggle.md)
4+
* Authors: [Chris Eidhof](http://chris.eidhof.nl)
5+
* Review Manager: [Ben Cohen](https://github.com/airspeedswift/)
6+
* Status: **Active review (February 12-19)**
7+
8+
9+
## Introduction
10+
11+
I propose adding a `mutating func toggle` to `Bool`. It toggles the `Bool`.
12+
13+
- Swift-evolution thread: [Discussion thread topic for that proposal](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20180108/042767.html)
14+
- Swift forums thread: [pitch: adding toggle to Bool](https://forums.swift.org/t/pitch-adding-toggle-to-bool/7414)
15+
16+
## Motivation
17+
18+
For `Bool` variables, it is common to want to toggle the state of the variable. In larger (nested) structs, the duplication involved can become especially annoying:
19+
20+
```swift
21+
myVar.prop1.prop2.enabled = !myVar.prop1.prop2.enabled
22+
```
23+
24+
It's also easy to make a mistake in the code above if there are multiple `Bool` vars.
25+
26+
## Proposed solution
27+
28+
Add a method `toggle` on `Bool`:
29+
30+
```swift
31+
extension Bool {
32+
/// Equivalent to `someBool = !someBool`
33+
///
34+
/// Useful when operating on long chains:
35+
///
36+
 /// myVar.prop1.prop2.enabled.toggle()
37+
 mutating func toggle() {
38+
self = !self
39+
}
40+
}
41+
```
42+
43+
This allows us to write the example above without duplication:
44+
45+
```swift
46+
myVar.prop1.prop2.enabled.toggle()
47+
```
48+
49+
`!` and `toggle()` mirror the API design for `-` and `negate()`. (Thanks to Xiaodi Wu for pointing this out).
50+
51+
## Detailed design
52+
53+
N/A
54+
55+
## Source compatibility
56+
57+
This is strictly additive.
58+
59+
## Effect on ABI stability
60+
61+
N/A
62+
63+
## Effect on API resilience
64+
65+
N/A
66+
67+
## Alternatives considered
68+
69+
Other names could be:
70+
71+
- `invert`
72+
- `negate`
73+
- `flip`
74+
75+
From the brief discussion on SE, it seems like `toggle` is the clear winner.
76+
77+
Some people also suggested adding a non-mutating variant (in other words, a method with the same semantics as the prefix `!` operator), but that's out of scope for this proposal, and in line with commonly rejected proposals.

0 commit comments

Comments
 (0)