Swift 3 - dynamic vs @objc

前端 未结 3 757
轮回少年
轮回少年 2020-12-13 17:25

What\'s the difference between marking a method as @objc vs dynamic, when would you do one vs the other?

Below is Apple\'s definition for dynamic.

3条回答
  •  悲哀的现实
    2020-12-13 17:59

    A function/variable declared as @objc is accessible from Objective-C, but Swift will continue to access it directly via static or virtual dispatch. This means if the function/variable is swizzled via the Objective-C framework, like what happens when using Key-Value Observing or the various Objective-C APIs to modify classes, calling the method from Swift and Objective-C will produce different results.

    Using dynamic tells Swift to always refer to Objective-C dynamic dispatch. This is required for things like Key-Value Observing to work correctly. When the Swift function is called, it refers to the Objective-C runtime to dynamically dispatch the call.

提交回复
热议问题