与 Swift 3.1 deprecates initialize(). How can I achieve the same thing? 遇到同样的问题,@Jordan Smith 的解决方案非常令人印象深刻,当时我对实现很感兴趣,但是在实践中遇到了一些麻烦,这里有一些关键代码,看评论,为什么UIViewController
中的日志功能是没有被调用,它符合协议(protocol);为什么 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)
}()
最佳答案
嗯,看起来 UIViewController 的 swift 扩展在使用 objc 方法时不可见。 所以这是我基于 this topic 的解决方案.
首先,您需要使用 @objc
关键字标记 Conscious
协议(protocol)。
@objc protocol Conscious {
static func awake()
}
然后你需要使用class_conformsToProtocol
-function。
let type = types[index]!
if class_conformsToProtocol(type, Conscious.self) {
let item = type as! Conscious.Type
item.awake()
}
关于swift - 对 swift 中的类型判断感到困惑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43348372/