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

Kevin Ballard kevin at sb.org
Thu Dec 10 18:31:37 CST 2015


On Thu, Dec 10, 2015, at 02:24 AM, Brent Royal-Gordon wrote:
> 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.

Yes it does. When message dispatch is done using the obj-c runtime, the compiler is free to omit the message send and use static dispatch if it believes it knows the concrete type of the receiver. This normally behaves the same, because dynamic dispatch with a known receiver type and static dispatch are the same, except if the method is dynamically replaced using the obj-c runtime methods, the static dispatch will not invoke the dynamically overridden method. The most common way you see this is with KVO. If you try and KVO an @objc property on a Swift object, it may work sometimes and may not work at other times, depending on when the compiler believes it can safely use static dispatch. This is why Swift has a whole keyword called `dynamic` whose job is to say "no really, use dynamic dispatch for every single access to this method/property, I don't care that you know for a fact it's a Foo and not a subclass, just trust me on this".

More generally, I don't see there being any real difference between

extension Proto {
    func someMethodNotDefinedInTheProto()
}

and saying

func someFuncThatUsesTheProto<T: Proto>(x: T)

except that one is invoked using method syntax and one is invoked using function syntax. Method invocation syntax does not inherently mean "dynamic dispatch" any more than function syntax does.

-Kevin Ballard


More information about the swift-evolution mailing list