Skip to content
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
Cannot retrieve contributors at this time

Adding toggle to Bool


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


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:

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:

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:


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

Detailed design


Source compatibility

This is strictly additive.

Effect on ABI stability


Effect on API resilience


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.