Does Swift have dynamic dispatch and virtual methods?

Ian Ringrose picture Ian Ringrose · Jun 3, 2014 · Viewed 10.2k times · Source

Coming form a C++/Java/C# background I was expecting to see virtual methods in Swift, however reading the swift documentation I see no mention of virtual methods.

What am I missing?


Due to large number of views, I have decided to offer a reward for an upto date and very clear/detail answer.

Answer

Jasper Blues picture Jasper Blues · Aug 22, 2014

Unlike C++, it is not necessary to designate that a method is virtual in Swift. The compiler will work out which of the following to use:

(the performance metrics of course depend on hardware)

  • Inline the method : 0 ns
  • Static dispatch: < 1.1ns
  • Virtual dispatch 1.1ns (like Java, C# or C++ when designated).
  • Dynamic Dispatch 4.9ns (like Objective-C).

Objective-C of course always uses the latter. The 4.9ns overhead is not usually a problem as this would represent a small fraction of the overall method execution time. However, where necessary developers could seamlessly fall-back to C or C++. In Swift, however the compiler will analyze which of the fastest can be used and try to decide on your behalf, favoring inline, static and virtual but retaining messaging for Objective-C interoperability. Its possible to mark a method with dynamic to encourage messaging.

One side-effect of this, is that some of the powerful features afforded by dynamic dispatch may not be available, where as this could previously have been assumed to be the case for any Objective-C method. Dynamic dispatch is used for method interception, which is in turn used by:

  • Cocoa-style property observers.
  • CoreData model object instrumentation.
  • Aspect Oriented Programming

The kinds of features above are those afforded by a late binding language. Note that while Java uses vtable dispatch for method invocation, its still considered a late binding language, and therefore capable of the above features by virtue of having a virtual machine and class loader system, which is another approach to providing run-time instrumentation. "Pure" Swift (without Objective-C interop) is like C++ in that being a direct-to-executable compiled language with static dispatch, then these dynamic features are not possible at runtime. In the tradition of ARC, we might see more of these kinds of features moving to compile time, which gives an edge with regards to "performance per watt" - an important consideration in mobile computing.