Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the opposite value of a Bool in Swift?

Tags:

ios

swift

boolean

My specific case is I am trying to toggle the nav bar hidden and showing.

    let navHidden = !self.navigationController?.navigationBarHidden
    self.navigationController?.setNavigationBarHidden(navHidden!, animated: true)

Is not working for me like it normally would in Obj-C.

like image 374
SirRupertIII Avatar asked Sep 14 '14 02:09

SirRupertIII


People also ask

How do you get the opposite of a boolean value?

The "and" ( && ) operator returns true if the boolean value to its left and the boolean value to its right are true. And the "not" ( ! ) operator returns the opposite of the boolean value to its right. That is, true becomes false and false becomes true .

How do you negate a boolean in Swift?

Swift NOT Operator ! is used to perform logical NOT operation on a boolean operand. ! symbol is used for Logical NOT Operator in Swift. NOT Operator takes one boolean value as operands on its right and returns the logical NOT of the operand.

How do you change boolean to opposite?

To toggle a boolean, use the strict inequality (! ==) operator to compare the boolean to true , e.g. bool !== true . The comparison will return false if the boolean value is equal to true and vice versa, effectively toggling the boolean.


2 Answers

The exclamation point is on the wrong side of the boolean. The way you've written it would indicate that the boolean could be nil. You want !navHidden.

like image 129
Ideasthete Avatar answered Oct 10 '22 05:10

Ideasthete


navHidden! is to make sure this is not optional. !navHidden is the correct way to do that.

From Apple's book.

Trying to use ! to access a non-existent optional value triggers a runtime error. Always make sure that an optional contains a non-nil value before using ! to force-unwrap its value.

like image 26
erickg Avatar answered Oct 10 '22 05:10

erickg