1
votes

I recently downloaded this project and converted it to the latest swift syntax. I can't understand why I continue to get the error "Initializer for conditional binding must have Optional type, not "UIView"

Error is occuring on line:

let containerView = transitionContext.containerView

Here is the full code:

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
    guard
        let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
        let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to),
        let containerView = transitionContext.containerView
        else {
            return

    }

    containerView.insertSubview(toVC.view, belowSubview: fromVC.view)

    let screenBounds = UIScreen.main.bounds
    let bottomLeftCorner = CGPoint(x: 0, y: screenBounds.height)
    let finalFrame = CGRect(origin: bottomLeftCorner, size: screenBounds.size)

    UIView.animate(
        withDuration: transitionDuration(using: transitionContext),
        animations: {
            fromVC.view.frame = finalFrame
        },
        completion: { _ in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
        }
    )
}
1
just move let containerView = transitionContext.containerView out of the guard statement and put it above containerView.insertSubview(toVC.view, belowSubview: fromVC.view) - Leo Dabus

1 Answers

0
votes

It is because containerView property is not an Optional type. As you can see here (which is taken from the documentation (command + LMB) on UIViewControllerContextTransitioing):

...
public protocol UIViewControllerContextTransitioning : NSObjectProtocol {


    // The view in which the animated transition should take place.

    @available(iOS 2.0, *)
    public var containerView: UIView { get }
...

You can place the erroneous line after the guard statement.