Skip to content

Bool toggle proposal #782

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 12, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions proposals/0199-bool-toggle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Adding `toggle` to `Bool`

* Proposal: [SE-0199](0199-bool-toggle.md)
* Authors: [Chris Eidhof](http://chris.eidhof.nl)
* Review Manager: [Ben Cohen](https://github.com/airspeedswift/)
* Status: **Active review (February 12-19)**


## Introduction

I propose adding a `mutating func toggle` to `Bool`. It toggles the `Bool`.

- Swift-evolution thread: [Discussion thread topic for that proposal](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20180108/042767.html)
- Swift forums thread: [pitch: adding toggle to Bool](https://forums.swift.org/t/pitch-adding-toggle-to-bool/7414)

## Motivation

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:

```swift
myVar.prop1.prop2.enabled = !myVar.prop1.prop2.enabled
```

It's also easy to make a mistake in the code above if there are multiple `Bool` vars.

## Proposed solution

Add a method `toggle` on `Bool`:

```swift
extension Bool {
/// Equivalent to `someBool = !someBool`
///
/// Useful when operating on long chains:
///
 /// myVar.prop1.prop2.enabled.toggle()
 mutating func toggle() {
self = !self
}
}
```

This allows us to write the example above without duplication:

```swift
myVar.prop1.prop2.enabled.toggle()
```

`!` and `toggle()` mirror the API design for `-` and `negate()`. (Thanks to Xiaodi Wu for pointing this out).

## Detailed design

N/A

## Source compatibility

This is strictly additive.

## Effect on ABI stability

N/A

## Effect on API resilience

N/A

## Alternatives considered

Other names could be:

- `invert`
- `negate`
- `flip`

From the brief discussion on SE, it seems like `toggle` is the clear winner.

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.