Boolean is one of the most frequently used and simplest data type in any programming language.

It is common to want to toggle the state of the boolean variable. So, we normally do it like this,

private var isEnabled = trueif isEnabled == true {
 isEnabled = false
}
print(isEnabled) // Prints false

The above approach is common but there will be cases where the boolean value should be toggled frequently. Explicitly assigning the boolean to true or false can be error prone. In Swift, we can use the toggle() method to toggle the value of a boolean.

private var isEnabled = true
if isEnabled == true{
 isEnabled.toggle()
}
print(isEnabled) // Prints false

Though it is simple, it will be very beneficial in cases which involves complex data structures like,

floatingView.panel.shouldScroll.toggle()

Playground sample,

Toggle() method in Swift boolean

Follow me on Twitter. Have any queries? Feel free to DM me.