Do you use all power of Bool? Let's see

Boolean data type is one of the basic data type in computer science. In our development daily routine we are using a Bool many times each day.

In article I want to show that one minute of reading documentation can make daily code more elegant.

Yes, I spent 1 minute to read documentation. After it, I hopefully started writing code better. Or maybe not, who knows 😀

Let’s go to real cases:

1 Routine case: Make a Bool variable opposite in value.

Regular way:

view.isHidden = !view.isHidden
isCollapsed = !isCollapsed

Preferred way:

view.isHidden.toggle()
isCollapsed.toggle()

Bool instance has out of box toggle() function. toggle() - toggles the boolean variable’s value.

2 Routine case: Get random Bool:

Possible way:

[true, false].randomElement()
// Or
func randomBool() -> Bool {
    return arc4random_uniform(2) == 0
}

Preferred way:

Bool.random()

Bool has out of box random() function.

Bool official Apple documentation

Thanks for reading! See you soon. 👋