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

12,645

Solution 1

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.

Solution 2

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.

Solution 3

navHidden is an optional. And you explictely unwrap that optional (which means you get a crash if navHidden is nil). Clearly something is wrong here. I suggest

if let navController = self.navigationController {
    let navHidden = navController.navigationBarHidden
    navController.setNavigationBarHidden (!navHidden, animated:true)
}
Share:
12,645
SirRupertIII
Author by

SirRupertIII

Updated on June 20, 2022

Comments

  • SirRupertIII
    SirRupertIII almost 2 years

    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.

  • SirRupertIII
    SirRupertIII over 9 years
    Thanks! I wasn't trying to invert it twice. It won't compile unless I have the ! on the right. This is what is working for me: let navHidden = self.navigationController?.navigationBarHidden self.navigationController?.setNavigationBarHidden(!navHidden‌​!, animated: true)
  • Ideasthete
    Ideasthete over 9 years
    Ah, gotcha. Removed that part of my comment.