该函数的声明说,fromVC
是可选的(这是什么?
后缀的意思),那toVC
是不可选的(因为它没有?
后缀).只有一个Optional
可以nil
.
另外,常见的Swift风格是使用an if-let
来打开可选项.试试这个:
private func switchViewController(from fromVC: UIViewController?, to toVC: UIViewController) { if let fromVC = fromVC { // In this scope, fromVC is a plain UIViewController, not an optional. fromVC.willMoveToParentViewController(nil) fromVC.view.removeFromSuperview() fromVC.removeFromParentViewController() } self.addChildViewController(toVC) self.view.insertSubview(toVC.view, atIndex: 0) toVC.didMoveToParentViewController(self) }