Swift3 条件绑定的初始值设定项必须具有可选类型,而不是;UIView“;

Swift3 条件绑定的初始值设定项必须具有可选类型,而不是;UIView“;,swift3,Swift3,我最近下载了这个项目,并将其转换为最新的swift语法。我不明白为什么我继续得到错误“条件绑定的初始值设定项必须具有可选类型,而不是“UIView” 第行发生错误: let containerView = transitionContext.containerView 以下是完整的代码: func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard

我最近下载了这个项目,并将其转换为最新的swift语法。我不明白为什么我继续得到错误“条件绑定的初始值设定项必须具有可选类型,而不是“UIView”

第行发生错误:

let containerView = transitionContext.containerView
以下是完整的代码:

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)
        }
    )
}

这是因为
containerView
属性不是可选类型。正如您在这里看到的(取自
UIViewControllerContextTransitioning
上的文档(command+LMB)):


您可以将错误行放在
guard
语句之后。

这是因为
containerView
属性不是可选类型。如您所见(取自
UIViewControllerContextTransitioning
上的文档(command+LMB)):


您可以将错误的行放在
guard
语句之后。

只需将
让containerView=transitionContext.containerView
移出guard语句,并将其放在
containerView.insertSubview(toVC.view,belowSubview:fromVC.view)上方即可
只需将containerView=transitionContext.containerView从guard语句中移出,并将其放在
containerView.insertSubview(toVC.view,belowSubview:fromVC.view)上方即可
...
public protocol UIViewControllerContextTransitioning : NSObjectProtocol {


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

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