0Pricing
Swift Academy · Lesson

Boolean Methods and Toggling

Use toggle() and Boolean-returning methods.

Bool Has Methods Too

In Swift even a Bool is a type with useful methods. The most common is toggle(), which flips the value in place.

var isOn = false
isOn.toggle()
print(isOn)

Toggle vs Manual Flip

Before toggle() existed, people wrote isOn = !isOn. The method version is shorter and avoids repeating the variable name.

var darkMode = true
darkMode.toggle()
print(darkMode)
darkMode.toggle()
print(darkMode)

All lessons in this course

  1. Bool Values and Expressions
  2. The Ternary Conditional Operator
  3. Avoiding Nested Ternaries
  4. Boolean Methods and Toggling
← Back to Swift Academy