UIViewController 的条件转换总是成功 | Swift/Xcode

Conditional cast from UIViewController always succeeds | Swift/Xcode

我在这里做错了什么?这仍然可以正常工作,但如果可以的话,我想摆脱黄色警告。警告在“if”语句中。如果我删除“?”在“as”上,那么代码甚至不会 运行...它需要它却抱怨它。

警告:

Conditional cast from 'UIViewController' to 'UIViewController' always succeeds

代码:

class FadeInPushSegue: UIStoryboardSegue {
    
    var animated: Bool = true
    
    override func perform() {
        
        if let sourceViewController = self.source as? UIViewController, let destinationViewController = self.destination as? UIViewController {
            
            let transition: CATransition = CATransition()
            
            transition.type = CATransitionType.fade; sourceViewController.view.window?.layer.add(transition, forKey: "kCATransition")
            sourceViewController.navigationController?.pushViewController(destinationViewController, animated: false)
        }
        
    }

}

您不需要将其转换为 UIViewController,因为属性源和目标已经是 UIViewController

open var source: UIViewController { get }

open var destination: UIViewController { get }

您看到此警告是因为您从非可选 UIViewController 转换为可选 UIViewController。

当您删除 as? 时,您的代码不是 运行 因为您试图解包不是可选的 属性。

Initializer for conditional binding must have Optional type, not 'UIViewController'

你应该删除 if 做这样的事情:

final class FadeInPushSegue: UIStoryboardSegue {
var animated: Bool = true

override func perform() {
    
    let sourceViewController = self.source
    let destinationViewController = self.destination
    
    let transition: CATransition = CATransition()
    
    transition.type = CATransitionType.fade; sourceViewController.view.window?.layer.add(transition, forKey: "kCATransition")
    sourceViewController.navigationController?.pushViewController(destinationViewController, animated: false)

}