- Proposal: SE-NNNN
- Authors: Chris Eidhof
- Review Manager: TBD
- Status: Awaiting review
During the review process, add the following fields as needed:
- Decision Notes: Rationale, Additional Commentary
I propose adding a mutating func toggle
to Bool
. It toggles the Bool
.
Swift-evolution thread: Discussion thread topic for that proposal
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.
Add a method toggle
on Bool
:
extension Bool {
mutating func toggle() {
self = !self
}
}
This allows us to write the example above without duplication:
myVar.prop1.prop2.enabled.toggle()
N/A
This is strictly additive.
N/A
N/A
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.