与Swift 3.1 deprecates initialize(). How can I achieve the same thing?遇到同样的问题,@ Jordan Smith的解决方案非常令人印象深刻,然后我对这个工具很感兴趣,但在实践中遇到了一些麻烦,这里有一些关键代码,请看评论,为什么UIViewController
中的日志功能未被调用,它符合协议;为什么UIViewController
被抓住了,T == UIViewController.self
是false
:
protocol Conscious {
static func awake()
}
/** extension */
extension UIViewController: Conscious {
static func awake() {
if self == UIViewController.self {
print(self, #function) // never came here, but seems should come
}
}
}
/** 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()
let T = types[index]!
let vc = UIViewController()
print(T, vc.isKind(of: T), T == UIViewController.self)
/*
Strange things:
UIResponder true false
UIViewController true false(why is false)
UISearchController false false
*/
}
types.deallocate(capacity: typeCount)
}()
答案 0 :(得分:0)
好吧,看起来使用objc
方法看不到UIViewController的swift扩展。
所以这是基于this topic的解决方案。
首先,您需要使用Conscious
关键字标记@objc
- 协议。
@objc protocol Conscious {
static func awake()
}
然后你需要使用class_conformsToProtocol
- 函数。
let type = types[index]!
if class_conformsToProtocol(type, Conscious.self) {
let item = type as! Conscious.Type
item.awake()
}