ios - swift 里的类型判断问题?
大家讲道理
大家讲道理 2017-04-18 09:57:49
0
0
708

swift 升级到 3.1 后遇到了警告,initialize() 将会在未来废弃,我在 stackoverflow 上找到了一个让人印象深刻的讨论,但在实践中的遇到了一些问题:

具体的代码如下,有兴趣的可以在 playground 跑一下,问题在注释里:

protocol Conscious {
    static func awake()
}

/** extension */
extension UIViewController: Conscious {
    static func awake() {  
        if self == UIViewController.self {  // 这里每个 UIViewController 的子类都调用了
            print(self, #function)          // 这里从没被调用
        }
    }
}

/** main */
private static let _operation: Void = {
    let typeCount = Int(objc_getClassList(nil, 0))
    let types = UnsafeMutablePointer<AnyClass?>.allocate(capacity: typeCount)
    let autoreleasingTypes = AutoreleasingUnsafeMutablePointer<AnyClass?>(types)
    objc_getClassList(autoreleasingTypes, Int32(typeCount))

    for index in 0 ..< typeCount {
        (types[index] as? Conscious.Type)?.awake()
        
        if let t = types[index] as? Conscious.Type {
            print(t)  // 所有 UIViewController 的子类都打印了,它自己没有被打印
        }

        let T = types[index]!
        let vc = UIViewController()
        print(T, vc.isKind(of: T), T == UIViewController.self)
        /*
          奇怪的打印:
          UIResponder true false
          UIViewController true false(why is false)
          UISearchController false false
         */
    }

    types.deallocate(capacity: typeCount)
}()
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(0)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template