[swift-evolution] Proposal: Universal dynamic dispatch for method calls

Brent Royal-Gordon brent at architechies.com
Thu Dec 10 04:24:34 CST 2015


>> 2) Swift’s general slant is towards using virtual dispatch unless it’s forbidden. (Leaving aside cases where the optimizer can prove at compile time what a dynamic dispatch would do.) That’s why we have a `final` keyword instead of a `virtual` keyword. Because of this, it’s not surprising to Swift users that you *can* override some extension methods; rather, the surprise is that you *can’t* override others. (And the *real* surprise is that you can kind-of-but-not-really override them, and Swift doesn’t complain.) I want developers to mark the surprise.
> 
> I don't agree that Swift's general slant is towards using virtual dispatch. Only classes and protocol objects use virtual dispatch[1]. And Swift even provides a mechanism (final / static) to remove dynamic dispatch from classes. It seems to me that Swift's general slant is towards encouraging static dispatch whenever possible.

I quite disagree here.

Swift loves to dispatch things statically and does so wherever possible. In some cases—such as value types not having inheritance—language features are clearly designed the way they are specifically to allow them to be statically dispatched. But Swift never uses static dispatch where dynamic dispatch would have given a different result. This contrasts with, for instance, a non-virtual C++ method’s behavior of “ha ha ha, I’m just going to ignore your override for speed." You could write a Swift compiler which dispatched everything dynamically, and you would never see any difference in semantics.

The sole exception to this rule is protocol extensions. There, we see static behavior with no explicit request for it. That’s why I think there *should* be a keyword requesting static behavior in this context—because it turns the static behavior into a feature rather than a bug.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list