toggle(): Toggle boolean value of a variable in Swift


In Swift programming, we can use the toggle() method to toggle a boolean value of a boolean type variable.

For example, suppose we have a boolean type variable with the boolean value true. Now we can change the value from true to false just by applying the toggle() method to the variable you can see below:

variableName.toggle()

Now let’s see an example:

var isRaining = true

isRaining.toggle()

print(isRaining)

Output:

false

As you can see in the above example, after we toggle our Swift variable using the toggle() method, the boolean value of the variable has been changed. Now the value of the variable isRaining is false.

Now if we further use the toggle() method, it will again change the value into true. If the value is true, then it will change to false. On the other hand, if the value is false, the method will change the value to true.

Now let’s see in the example below where using toggle() method multiple times changing the boolean value again and again:

var isRaining = true

isRaining.toggle()
print(isRaining)

isRaining.toggle()
print(isRaining)

isRaining.toggle()
print(isRaining)

isRaining.toggle()
print(isRaining)

Output:

false
true
false
true

As you can see in the output of the above program, the value of isRaining changes every time because we are applying toggle() method every time before printing the variable.

This is exactly toogle() does. I hope you have now a clear idea of using the toggle() method in Swift to toggle a boolean value.