Search code examples
iosswiftxcodecastingoption-type

Conditional cast from UIViewController always succeeds | Swift/Xcode


What am I doing wrong here? This still functions fine, but I would like to get rid of the yellow warning if I can help it. The warning is on the "if" statement. If I remove the "?" on "as", then the code won't even run... it requires it yet complains about it.

The warning:

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

The code:

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

}

Solution

  • You don't need to cast it to UIViewController because properties source and destinations is UIViewController already

    open var source: UIViewController { get }
    
    open var destination: UIViewController { get }
    

    You seeing this warning because you cast from not Optional UIViewController to optional UIViewController.

    When you remove as? your code isn't running because you trying to unwrap not optional property.

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

    You should remove if do something like that:

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