iOS Swift3 check nil value for ViewController Object

前端 未结 6 1788
面向向阳花
面向向阳花 2021-01-28 09:16
let viewControllers: [UIViewController] = self.navigationController!.viewControllers

for VC  in viewControllers  {            
    if (VC.isKind(of: HomeViewController.         


        
6条回答
  •  失恋的感觉
    2021-01-28 09:42

    Never use directly ! until you are damn sure that it will not be nil. Replace your code as below. You can use if let or guard let to unwrap optionals.

        if let viewControllers: [UIViewController] = self.navigationController?.viewControllers {
                    for VC  in viewControllers  {
    
                        if (VC.isKind(of: ViewController.self)) {
    
                            bScreen = true
                            self.navigationController?.popToViewController(VC, animated: true)
                        }
                    }
    
                    if bScreen == false
                    {
                        let homeVC = ViewController()
                        self.navigationController?.pushViewController(homeVC, animated: false)
                    }
     } 
    else {
         // IF VC is nil
    }
    

提交回复
热议问题