Ios swift中appDelegate的popToRootViewController

Ios swift中appDelegate的popToRootViewController,ios,objective-c,swift,Ios,Objective C,Swift,我试图从应用程序代理弹出到导航堆栈的根视图控制器,在将obj-c中的工作方式转换为swift时遇到一些问题 什么在obj-c中起作用: UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController; [navigationController popToRootViewControllerAnimated:YES]; 我的转换尝试: var n

我试图从应用程序代理弹出到导航堆栈的根视图控制器,在将obj-c中的工作方式转换为swift时遇到一些问题

什么在obj-c中起作用:

UINavigationController *navigationController = (UINavigationController  *)self.window.rootViewController;
[navigationController popToRootViewControllerAnimated:YES];
我的转换尝试:

  var navigationController: UINavigationController = self.window?.rootViewController;
        navigationController.popToRootViewControllerAnimated(true);
我在说UIViewController时出错?不可转换为UINavigationController的


我该如何解决这个问题?

这里有几件事:

1) rootViewController将作为可选属性返回,因为窗口和rootViewController属性都是可选的。因此,我们需要将其展开,以确保这些值实际存在

2) rootViewController定义为UIViewController,而不是UINavigationController子类。我们需要将其转换为UINavigationController,以便能够作为一个整体对其进行操作

尝试将根视图控制器作为UINavigationController安全地展开:

if let navigationController = self.window?.rootViewController as? UINavigationController {
        navigationController.popToRootViewController(animated: true)
}
swift 3使用以下命令:

  _ = navigationController?.popToRootViewController(animated: true)