You must have come across @objc and dynamic keyword while coding in Swift. The compiler gives an error if you are not using @objc when it is needed. A developer may have a list of questions in mind :

  1. Where these keywords used?
  2. Why use @objc in a project which is purely in Swift? As it seems @objc is something related to Objective-C
  3. How methods behave with and without @objc behind the scene.
  4. Exact purpose of dynamic?
  5. Does dynamic also affects the time of execution of a program?

We are going to cover above in detail using a proper example.

“@objc”

Swift generates code that is only readable to other Swift code. But if we need to interact with the Objective-C runtime, we need to instruct Swift what to do. Here comes@objc to make swift code available to Objective-C. Have you ever wonder why to prefix @objc even if the code is written purely in Swift? The answer is, although you may have whole code in Swift there are some frameworks that use Objective-C runtime — UIKit is one of them. Simply we can say @objc means we want our Swift code (class, method, property, etc.) to be visible from Objective-C.”

You must have noticed that we need to add the prefix @objc for #selector(function) in case of adding target to Button, UITabGestureRecogniser or Timer. This is because the **Selector **is a C string that represents the name of the method at the runtime. For C string we have to invoke Objective-C runtime.


“dynamic”

Use of “dynamic” in Swift code requires when we want to use Objective-C dynamic dispatch. We may need this for KVO support or if we are doing method swizzling.

I am not going in detail of Method Swizzling as this is not in scope of this article. In simple words: Method Swizzling is the ability that Objective-C runtime gives us, to switch the implementation of an existing selector at runtime.

Note : As dynamic is Objective-C feature, we have to use @objc also when we use dynamic keyword.

#objc #ios #ios-app-development #swift #objective-c #programming-c

To the depth of @objc and dynamic in Swift
1.40 GEEK