方法在swift 4中调整

Chr*_*Rex 6 swizzling swift method-swizzling swift4

Swift 4中的混合不再有效.

Method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift

这是我找到解决方案的事情所以想留下问题和答案给别人.

Chr*_*Rex 6

initialize()不再暴露: Method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift

所以现在的方法是通过公共静态方法运行你的混合代码.

例如

在扩展中:(此扩展用于kickstarted开源代码:https://github.com/kickstarter/ios-oss/blob/master/Library/DataSource/UIView-Extensions.swift)

private var hasSwizzled = false

extension UIView {
    final public class func doBadSwizzleStuff() {
        guard !hasSwizzled else { return }

        hasSwizzled = true
        swizzle(self) /* This is pseudo - run your method here */
    }
}
Run Code Online (Sandbox Code Playgroud)

在app delegate中:(此方法用于kickstarted开源代码:https://github.com/kickstarter/ios-oss/blob/7c827770813e25cc7f79a28fa151cd713efe936f/Kickstarter-iOS/AppDelegate.swift#L33)

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: UIApplicationLaunchOptionsKey: Any]?) -> Bool 
{
    UIView.doBadSwizzleStuff()
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用单身人士:

extension UIView {
    static let shared : UIViewController = {
        $0.initialize()
        return $0
    }(UIViewController())

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

        let swizzleClosure: () = {
            UIViewController().swizzle() /* This is pseudo - run your method here */
        }()
        swizzleClosure
    }
}

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: UIApplicationLaunchOptionsKey: Any]?) -> Bool 
{
    _  = UIViewController.shared
}
Run Code Online (Sandbox Code Playgroud)

  • 这只有在您有权访问AppDelegate源代码时才有效.我正在编写一个库,并希望利用Swizzling在ViewController的"viewDidLoad"块中运行特定的方法.我正在尝试让我的库尽可能简单地让客户实现,虽然我可以要求他们将代码添加到AppDelegate,但如果可能的话我宁愿使用Swizzling(如果需要,可以选择禁用它).有关这方面的任何想法让Swift 4.0中的"AppDelegate免费"调整?谢谢!克雷格 (2认同)