Optional binding succeeds if it shouldn't

前端 未结 1 1824
执笔经年
执笔经年 2020-12-05 21:02

This is what I posted as a possible solution to Traverse view controller hierarchy in Swift (slightly modified):

extension UIViewController {

    func trave         


        
相关标签:
1条回答
  • 2020-12-05 21:21

    If you try to conditionally cast an object of type UINavigationController to a UICollectionViewController in a Playground:

    var nc = UINavigationController()
    
    if let vc = nc as? UICollectionViewController {
        println("Yes")
    } else {
        println("No")
    }
    

    You get this error:

    Playground execution failed: :33:16: error: 'UICollectionViewController' is not a subtype of 'UINavigationController' if let vc = nc as? UICollectionViewController {

    but if instead you do:

    var nc = UINavigationController()
    
    if let vc = (nc as Any) as? UICollectionViewController {
        println("Yes")
    } else {
        println("No")
    }
    

    it prints "No".

    So I suggest trying:

    extension UIViewController {
    
        func traverseAndFindClass<T where T : UIViewController>(T.Type) -> T? {
            var currentVC = self
            while let parentVC = currentVC.parentViewController {
                println("comparing \(parentVC) to \(T.description())")
                if let result = (parentVC as Any) as? T { // (XXX)
                    return result
                }
                currentVC = parentVC
            }
            return nil
        }
    }
    
    0 讨论(0)
提交回复
热议问题