Blog

Swift Tip: Adding a toggle Extension on 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.

You can solve this problem by adding a method toggle on Bool:

								extension Bool {
   mutating func toggle() {
       self = !self
   }
}

							

This allows us to write the example above without duplication, and with clear intent:

								myVar.prop1.prop2.enabled.toggle()

							

Much better 😊

This won't always transfer to other languages, but Swift's mutable self makes it very useful. So useful in fact that we proposed it as an extension to the Swift Standard Library.

Anyone in the community can discuss or submit a proposal. If you're new to the process, and you'd like to make a suggestion, start by reading the Contributing Guidelines, and the Swift Evolution Process document.

Until this week, all discussion happened on the swift-evolution mailing list. From Wednesday, January 17, 6PM Pacific, the mailing lists will be suspended, and a few days later the new Swift Discourse forum will take up the mantle. You can join the forum today. 🎉

Our thanks to @PublicExtension for pointing out a similar extension by @Kametrixom (and to Jasdev for writing it up!).

To learn more about mutation and structs, watch Swift Talk Episode 21 or read the transcript. If you'd like to learn more about Swift's powerful features for dealing with mutability, read our book, Advanced Swift.

  • Watch the Full Episode

    Swift, the Language

    Structs and Mutation

    We can change structs by mutation, functional chaining, and inout parameters. We discuss how they differ at the call site and why they’re all equivalent.

    Episode 21 · October 21, 2016

  • See the Swift Talk Collection

Stay up-to-date with our newsletter or follow us on Twitter .

Back to the Blog

Recent Posts