[英]Value of type 'NSPersistentStore' can never be nil, comparison isn't allowed
[英]Value of type UIViewController can never be nil, comparison isn't allowed
我正在遵循有关Multiview应用程序的教程,并且说要在其中一个视图控制器中编写此功能。 我在第二个if
语句上看到一个错误,该语句说UIViewController
不能为nil,并且不允许进行比较。 这是我不再需要担心的事情了吗? 这本书有点过时了,所以我假设它的出现是由于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)
}
}
该函数的声明说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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.