Swift 3 - dynamic vs @objc

前端 未结 3 723
轮回少年
轮回少年 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 18:03

    To work with Objective-C from Swift you have at least two reserved words:

    • @objc[About] - Compile time - To expose Swift's api for Objective-C runtime. For example a framework which was written on Swift can use @objc for:

      1. using #selector[About] in a Swift code
      2. opening public functionality for Objective-C consumers
    • dynamic - Run time - to enable a message dispatch(Objective-C's world) for NSObject object, which is different than virtual dispatch (table dispatch) (Swift's world). It is used for:

      1. KVO
      2. class extensions to have a possibility to override an extension function
      3. swizzling[Example]

    Before Swift v4 dynamic included @objc

提交回复
热议问题