swift - 对 swift 中的类型判断感到困惑?

标签 swift swift3

Swift 3.1 deprecates initialize(). How can I achieve the same thing? 遇到同样的问题,@Jordan Smith 的解决方案非常令人印象深刻,当时我对实现很感兴趣,但是在实践中遇到了一些麻烦,这里有一些关键代码,看评论,为什么UIViewController中的日志功能是没有被调用,它符合协议(protocol);为什么 UIViewController 被捕获,但 T == UIViewController.selffalse:

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/

相关文章:

ios - 动态设置放置在 UIScrollView 中的 UITableView 的框架大小

swift - UrbanAirship Cocoapods 无法与 use_frameworks 一起使用

ios - Swift 4 转换错误 - 类型 'NSAttributedStringKey' 没有成员 'foregroundColorNSAttributedStringKey'

swift - Swift 3 中的按钮无法单击导航栏后面

ios - 在 Swift 中使旋转真实地停止

ios - 以白色和透明背景模态呈现 UIViewController 时出现黑色伪影

swift - sum.swift :29:19: error: cannot find 'CFAbsoluteTimeGetCurrent' in scope

swift - 如何为自定义字体声明 NSAttributedStringKey.font?

ios - Swift 3 - UTC to time ago 标签,考虑 12h/24h 设备时间变化

swift - Swift 3.0 中的 IOS 颜色选择器