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
- Bool Values and Expressions
- The Ternary Conditional Operator
- Avoiding Nested Ternaries
- Boolean Methods and Toggling