Swift dynamic keyword

Time:2022-5-26

If you have experience in OC development, you must be familiar with the @ dynamic keyword in OC, which tells the compiler not to synthesize getter and setter methods for attributes.

Swift also has dynamic keyword, which can be used to modify variables or functions, and its meaning is completely different from OC. It tells the compiler to use dynamic distribution instead of static distribution. One characteristic that distinguishes OC from other languages is its dynamic nature. Any method call is actually message distribution, while swift tries to achieve static distribution as much as possible.

Therefore, variables / functions marked as dynamic will implicitly add the @ objc keyword, which will use OC’s runtime mechanism.

Although static distribution may be more efficient, some app analysis and statistics libraries need to rely on the characteristics of dynamic distribution and dynamically add some statistical code, which is difficult to complete under Swift’s static distribution mechanism. In this case, although using dynamic keyword will sacrifice some performance optimization obtained by using static distribution, it is still worth it.

Runtime dynamicApplication instance (used in method exchange)


The article is constantly updated. I hope it will be helpful to you. If you have any questions, you can leave a message for us to learn together