Swift 3 - dynamic vs @objc
As that quote says, dynamic
implies @objc
.
Unless you specify a class as being dynamic
, the compiler is free to optimize away and inline its methods. This brings huge performance benefits, but it means that you can't change those method implementations at run time. If you're planning to mess around with those methods at runtime using the reflection capabilities of the Objective C runtime, you'll need to use dynamic
. You'll incur a performance penalty (your code will run at Objective C levels of speed, rather than near C-like levels), but you'll gain that extra dynamism.
Swift @objc and dynamic
[Objective C Runtime]
Swift
uses next reserved words for working with Objective-C
:
@objc
[About] - Compile time - To expose Swift's api for Objective-C runtime.- opening Swift public functionality for Objective-C consumers
- using
#selector
[About] in a Swift code
dynamic
- Run time - to enable amessage dispatch
[About](Objective-C's world) forNSObject
object, which is different than in Swift's world: class usestable dispatch (virtual dispatch)
and structProtocol Witness Table PWT
It is used for:
- [KVO]
class extensions
to have a possibility to override an extension function- swizzling[Example]
Pre Swift v4 dynamic
included @objc
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.