ios - swift 里的类型判断问题?

 玉乔嘉芸孟峰 发布于 2022-10-29 01:12

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.allocate(capacity: typeCount)
    let autoreleasingTypes = AutoreleasingUnsafeMutablePointer(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)
}()
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有