web-dev-qa-db-ja.com

メソッドのスウィズリングを実装する方法Swift 3.0?

Swift 3.0でスウィズルメソッドを実装するにはどうすればよいですか?

nshipster article を読んだことがありますが、このコードのチャンクで

struct Static {
    static var token: dispatch_once_t = 0
}

コンパイラからエラーが出ます

dispatch_once_tはSwiftでは利用できません:代わりに遅延初期化されたグローバルを使用してください

36

まず、_dispatch_once_t_はSwift 3.0では使用できません。次の2つの選択肢から選択できます。

  1. グローバル変数

  2. structenum、またはclassの静的プロパティ

詳細については、 Swift 3)のdispatch_onceがどこにあるか

異なる目的のために、スウィズリングの異なる実装を使用する必要があります

  • UIViewControllerなどのSwizzling CocoaTouchクラス。
  • Swizzling custom Swift class;

Swizzling CocoaTouchクラス

グローバル変数を使用したUIViewControllerviewWillAppear(_:)のスウィズルの例

_private let swizzling: (UIViewController.Type) -> () = { viewController in

    let originalSelector = #selector(viewController.viewWillAppear(_:))
    let swizzledSelector = #selector(viewController.proj_viewWillAppear(animated:))

    let originalMethod = class_getInstanceMethod(viewController, originalSelector)
    let swizzledMethod = class_getInstanceMethod(viewController, swizzledSelector)

    method_exchangeImplementations(originalMethod, swizzledMethod) }

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)")
    } 
 }
_

SwizzlingカスタムSwiftクラス

Swiftクラスでスウィズリングメソッドを使用するには、2つの要件に従う必要があります( 詳細 ):

  • スウィズルされるメソッドを含むクラスは、NSObjectを拡張する必要があります
  • スウィズルするメソッドには、dynamic属性が必要です。

そして、カスタムのスウィズリング方法の例Swift base class Person

_class Person: NSObject {
    var name = "Person"
    dynamic func foo(_ bar: Bool) {
        print("Person.foo")
    }
}

class Programmer: Person {
    override func foo(_ bar: Bool) {
        super.foo(bar)
        print("Programmer.foo")
    }
}

private let swizzling: (Person.Type) -> () = { person in

    let originalSelector = #selector(person.foo(_:))
    let swizzledSelector = #selector(person.proj_foo(_:))

    let originalMethod = class_getInstanceMethod(person, originalSelector)
    let swizzledMethod = class_getInstanceMethod(person, swizzledSelector)

    method_exchangeImplementations(originalMethod, swizzledMethod)
}

extension Person {

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

    // MARK: - Method Swizzling

    func proj_foo(_ bar: Bool) {
        self.proj_foo(bar)

        let className = NSStringFromClass(type(of: self))
        print("class: \(className)")
    }
}
_
56

@TikhonovAlexander:素晴らしい答え

スウィズラーを修正して両方のセレクターを取得し、より汎用的にしました。

Swift

private 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)
}

// perform swizzling in initialize()

extension UIView {

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

        let originalSelector = #selector(layoutSubviews)
        let swizzledSelector = #selector(swizzled_layoutSubviews)
        swizzling(self, originalSelector, swizzledSelector)
    }

    func swizzled_layoutSubviews() {
        swizzled_layoutSubviews()
        print("swizzled_layoutSubviews")
    }

}

Swift 4

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

extension UIView {

    static let classInit: Void = {            
        let originalSelector = #selector(layoutSubviews)
        let swizzledSelector = #selector(swizzled_layoutSubviews)
        swizzling(UIView.self, originalSelector, swizzledSelector)
    }()

    @objc func swizzled_layoutSubviews() {
        swizzled_layoutSubviews()
        print("swizzled_layoutSubviews")
    }

}

// perform swizzling in AppDelegate.init()

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    override init() {
        super.init()
        UIView.classInit
    }

}
28
efremidze

遊び場でスウィズル
Swift 4.2

import Foundation
class TestSwizzling : NSObject {
    @objc dynamic func methodOne()->Int{
        return 1
    }
}

extension TestSwizzling {

    //In Objective-C you'd perform the swizzling in load(),
    //but this method is not permitted in Swift
    func swizzle(){

        let i: () -> () = {

            let originalSelector = #selector(TestSwizzling.methodOne)
            let swizzledSelector = #selector(TestSwizzling.methodTwo)
            let originalMethod = class_getInstanceMethod(TestSwizzling.self, originalSelector);
            let swizzledMethod = class_getInstanceMethod(TestSwizzling.self, swizzledSelector)
            method_exchangeImplementations(originalMethod!, swizzledMethod!)
            print("swizzled")

        }
        i()
    }

    @objc func methodTwo()->Int{
        // It will not be a recursive call anymore after the swizzling
        return 4
    }
}

var c = TestSwizzling()
print([c.methodOne(),c.methodTwo()])
c.swizzle()
print([c.methodOne(),c.methodTwo()])

出力:
[1、4]
スウィズル
[4、1]

3
Dharay Mistry