Swift 5 Method Swizzling, @_dynamicReplacement

@_dynamicReplacement
方法替换:https://www.jianshu.com/p/b3778b953a35
不具体说了,就说一下上面的关键字怎么用:
这里有好多 demo

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        return true
    }
    
    dynamic func run(a: String) {
        print(a)
    }
    
    dynamic var a = 1
}

extension AppDelegate {
    @_dynamicReplacement(for: run(a:))
    func run_new(a: String) {
        print(self.a)
        run(a: "run new")
    }
    
    @_dynamicReplacement(for: a)
    var b: Int {
        a = a * 10
        return a
    }
}

@_dynamicReplacement 标记的方法中访问替换的方法或者对象, 就是原方法或者对象,在标记外的其他地方访问,走的是替换的方法。
即:
上面的代码,run_new 中访问的 self.a 走的是 bget 方法,但在 bget 方法中,访问的 a 是原属性 a

@_dynamicReplacement(for: a)
    var b: Int {
        a = a * 10
        return a
    }

你可能感兴趣的:(Swift 5 Method Swizzling, @_dynamicReplacement)