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

前端 未结 3 926
予麋鹿
予麋鹿 2021-01-18 15:02

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

    let navHidden = !self.navigationController?.navigationBarHidden
    self.naviga         


        
相关标签:
3条回答
  • 2021-01-18 15:03

    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.

    0 讨论(0)
  • 2021-01-18 15:20

    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)
    }
    
    0 讨论(0)
  • 2021-01-18 15:27

    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.

    0 讨论(0)
提交回复
热议问题