Objective-C Runtime and Swift @objcDynamic Interoperability
25.5K reputation · 29 Dec 2024, 07:19 UTC
Integrating Objective-C dynamic dispatch with Swift requires a balance between the flexibility of objc_msgSend and Swift's static optimization. While the @objc attribute exposes Swift members to the runtime, using @objc dynamic forces the use of the Objective-C message-sending mechanism for method invocation.
A design uncertainty arises when implementing runtime method swapping or category-based additions in Objective-C that must interact with Swift classes. If a Swift method is marked as dynamic, it allows the Objective-C runtime to redirect calls, but this may bypass the compiler's ability to devirtualize calls or perform inlining.
What are the specific performance trade-offs when replacing a Swift @objc dynamic method via the Objective-C runtime? Does this approach introduce overhead compared to standard Swift vtable dispatch in high-frequency execution paths?