What is the impact of using the @objc dynamic annotation in code?
sobes.tech AI
Answer from AI
The @objc dynamic annotation in Swift serves two main functions:
-
@objc — makes a method or property accessible to the Objective-C runtime. This is necessary if you want to use dynamic dispatch, interact with Objective-C APIs such as KVO (Key-Value Observing), selectors, or legacy code.
-
dynamic — forces the compiler to use dynamic dispatch via the Objective-C runtime instead of static or inline optimizations. This allows, for example, intercepting method calls, which is essential for KVO.
Together, @objc dynamic is typically used for properties and methods that need to support dynamic change observation (KVO) or be accessible from Objective-C.
Example:
class Person: NSObject {
@objc dynamic var name: String = ""
}
let person = Person()
var observation = person.observe(\.name, options: [.new]) { object, change in
print("Name changed to \(change.newValue ?? "")")
}
person.name = "Ivan" // Triggers the observer
Without @objc dynamic, KVO will not work, as the mechanism relies on the Objective-C runtime and dynamic dispatch.