I am following a tutorial on Multiview apps, and it said to write this function in one of the view controllers. I am getting an error on the second if
statement that says UIViewController
cant be nil, and comparison isn't allowed. Is this something I don't need to worry about anymore? The book is a little outdated so I'm assuming its occurring because of change in 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)
}
}
The declaration of the function says that fromVC
is optional (that's what the ?
suffix means), and that toVC
is not optional (because it has no ?
suffix). Only an Optional<UIViewController>
can be nil
.
Also, the common Swift style is to use an if-let
to unwrap the optional. Try this:
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)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.