14

I'm trying to read up on implementation details of Swift, and one thing I can't nail down are its "witness tables". It looks like they're a separate vtable pointer used for structs.

But why would you need that? Structs are copied by value, so you already know at compile-time what type they are. So wouldn't you just hard-code which method to call and be done with it? Why perform virtual dispatch on these methods?

uliwitness
  • 251
  • 2
  • 6
  • 1
    Can you point to some resources on those struct witness tables? All I have been able to find are protocol witness tables. – Jörg W Mittag Sep 25 '16 at 16:19

1 Answers1

15

Structs can implement interfaces, called protocols in Swift. You can have a parameter, variable, or field/member that is a protocol, and, because multiple different structs, not to mention classes, can implement that same protocol, once you pass (or assign) a struct to a protocol parameter (or variable or field), the specifics of which struct it might have been is "lost" (re: compile time) and the protocol witness table comes into play (re: runtime).

You can learn more about Swift memory layout.


Similar happens in C#, which I'm more familiar with. A struct passed or assigned to an interface variable or field/member is boxed, and the boxed representation of the struct matches that of class representations, which means there is a vtable for boxed structs.

I would expect both C# and Swift to make direct calls when the item is known at compile time as a struct, and to use vtable dispatch when at compile time, the item is only known as an interface.

Erik Eidt
  • 33,282
  • 5
  • 57
  • 91
  • 2
    "I would expect both C# and Swift to make direct calls when the item is known at compile time as a struct," yep, this is a process called *devirtualization* – Alexander Apr 30 '17 at 05:21
  • 3
    The above link does not work anymore. You probably want to reference https://github.com/apple/swift/blob/master/docs/ABI/TypeLayout.rst. – Martin R May 03 '18 at 13:49