类型UIViewController的值永远不能为零,不允许比较

时间:2015-12-23 17:21:37

标签: ios swift

我正在关注Multiview应用程序的教程,并且它说要在其中一个视图控制器中编写此函数。我在第if个语句中收到错误,该语句表示UIViewController不能为零,并且不允许进行比较。这是我不需要担心的事吗?这本书有点过时,所以我假设它是因为Swift的变化而发生的。

private func switchViewController(from fromVC: UIViewController?, to toVC: UIViewController) {
    if fromVC != nil {
        fromVC!.willMoveToParentViewController(nil)
        fromVC!.view.removeFromSuperview()
        fromVC!.removeFromParentViewController()
    }

    if toVC != nil {
        self.addChildViewController(toVC)
        self.view.insertSubview(toVC.view, atIndex: 0)
        toVC.didMoveToParentViewController(self)
    }
}

1 个答案:

答案 0 :(得分:5)

函数声明表明fromVC是可选的(?后缀的含义),而toVC 是可选的(因为它没有?后缀)。只有Optional<UIViewController>可以是nil

此外,常见的Swift风格是使用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)
}