iOS Swift3 check nil value for ViewController Object

前端 未结 6 1791
面向向阳花
面向向阳花 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:37

    This is better to use to if let / guard for an optional value to avoid crashing.

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

提交回复
热议问题