【问题标题】:Confused about type judgement in swift?对 swift 中的类型判断感到困惑?
【发布时间】:2017-05-05 20:58:54
【问题描述】:

遇到了Swift 3.1 deprecates initialize(). How can I achieve the same thing?同样的问题,@Jordan Smith 的解决方案很给力,然后我对工具很感兴趣,但是在实践中遇到了一些麻烦,这里有一些关键代码,见 cmets,为什么日志UIViewController 中的函数没有被调用,它符合协议;为什么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)
}()

【问题讨论】:

  • 你有什么问题?
  • @rmaddy 抱歉,请参阅代码中的 cmets
  • 好的,那你还有什么问题?
  • 为什么UIViewController中的日志函数没有被调用,它符合协议;为什么 UIViewController 被抓住了,但 T == UIViewController.self 是假的
  • 你应该改用===-operator

标签: swift swift3


【解决方案1】:

好吧,使用objc 方法看起来 UIViewController 的 swift 扩展是不可见的。 所以这是我基于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()
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    相关资源
    最近更新 更多