Swizzling CocoaTouch class in Swift 3.1

I am using Swift 3.1 in Xcode 8.3 and see this warning:

The 'initialize ()' method defines an Objective-C method of the 'initialize' class, which is not guaranteed to be called by Swift and will be prohibited in future versions

I use the Swizzling CocoaTouch class and have a problem with this part:

extension UIViewController {

    open override class func initialize() {
        // make sure this isn't a subclass
        guard self === UIViewController.self else { return }
        swizzling(self)
    }

    // MARK: - Method Swizzling

    func proj_viewWillAppear(animated: Bool) {
        self.proj_viewWillAppear(animated: animated)

        let viewControllerName = NSStringFromClass(type(of: self))
        print("viewWillAppear: \(viewControllerName)")
    } 
 }

How to rewrite this part of the code?

open override class func initialize()

to fix a new warning?

I saw the link, but I don’t understand how to use the information in my code.

+4
source share
1 answer

I had the same problem and fix it.

My decision

1. Change the swizzling () method for public from private

public let swizzling: (AnyClass, Selector, Selector) -> () = { forClass, originalSelector, swizzledSelector in
    let originalMethod = class_getInstanceMethod(forClass, originalSelector)
    let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector)
    method_exchangeImplementations(originalMethod, swizzledMethod)
}

2. Remove the initialize () method in extension UIViewController

//    open override class func initialize() {
//        // make sure this isn't a subclass
//        guard self === UIViewController.self else { return }
//        swizzling(self)
//    }

3. swizzling() AppDelegate:: didFinishLaunchingWithOptions

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    // some code

    swizzling(UIViewController.self)

    return true
}

/ . ( )

, . :  Swift 3.1 initialize(). ?

+3

Source: https://habr.com/ru/post/1673613/


All Articles