0

Met the same issue with Swift 3.1 deprecates initialize(). How can I achieve the same thing?, @Jordan Smith 's solution is very impressive, then i was interested in the implement, but met some troubles in practice, here are some key codes, see the comments, why the log function in UIViewController was not called, it conforms protocol; why UIViewController was caught but T == UIViewController.self is 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)
}()
Community
  • 1
  • 1
xiuxiuxiu
  • 11
  • 2

1 Answers1

0

Well, It looks like UIViewController's swift extensions are not visible using objc methods. So here is my solution based on this topic.

First you need to mark Conscious-protocol with @objc keyword.

@objc protocol Conscious {
    static func awake()
}

Then you need to use class_conformsToProtocol-function.

let type = types[index]!
if class_conformsToProtocol(type, Conscious.self) {
    let item = type as! Conscious.Type
    item.awake()
} 
Community
  • 1
  • 1
Daniyar
  • 2,975
  • 2
  • 26
  • 39