Maison > Questions et réponses > le corps du texte
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)
}()