dynamic modifier in functions in Swift
Asked Answered
S

1

13

According to Apple :

When you mark a member declaration with the dynamic modifier, access to that member is always dynamically dispatched. Because declarations marked with the dynamic modifier are dispatched using the Objective-C runtime, they’re implicitly marked with the @objc attribute.

According to Wikipedia:

dynamic dispatch is the process of selecting which implementation of a polymorphic operation (method or function) to call at run time.

Dynamic dispatch is often used in object-oriented languages when different classes contain different implementations of the same method due to common inheritance. For example, suppose you have classes A, B, and C, where B and C both inherit the method foo() from A. Now suppose x is a variable of class A. At run time, x may actually have a value of type B or C and in general you can't know what it is at compile time.

Right now, I'm studying the dependency injection framework : Typhoon and when I open the sample project for Swift in all the classes that inherit from the Objective-C class TyphoonAssembly all the methods relatives to inject dependencies have the dynamic modifier included in the following way :

public dynamic func weatherReportDao() -> AnyObject {
    return TyphoonDefinition.withClass(WeatherReportDaoFileSystemImpl.self)
}

I thought that I'm missing something, but I don't understand where is the polymorphic operation (method or function) to call at run time here.

What's is the purpose of the dynamic dispatch here?

Sneed answered 16/4, 2015 at 21:42 Comment(2)
Hmmm, the docs are a little weird there. When most of the world, including wikipedia, says “dynamic dispatch”, they usually mean the kind of runtime polymorphism that comes from overriding class methods. And in Swift, this happens without any need for the dynamic keyword, and will work 100% of the time despite what the docs darkly muter about inlining and devirtualization. But here, when they say dynamic, they mean the kind of crazy extra-dynamic runtime shenanigans you can get up to with objc_msgSend-type method dispatch.Maund
Without looking into the implementation of Typhoon, it's possible they've decided to use dynamic dispatch to make it KVO compliant for ease of use elsewhere. Michael Tsai's blog has an interesting discussion of dynamic here: http://mjtsai.com/blog/2014/08/18/its-a-coup/Unhouse
G
5

The answer to your question is addressed in this post:

https://github.com/appsquickly/typhoon/wiki/TyphoonAssembly

Basically at runtime the Typhoon Framework is going to replace your method with its own routine that implements the features of the framework and calls your method to do whatever work you've defined for it.

In order for the framework to be able to replace the method, the method must be dynamically dispatched.

Gearard answered 1/4, 2016 at 6:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.