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?

  • 1
    Can you point to some resources on those struct witness tables? All I have been able to find are protocol witness tables. Sep 25, 2016 at 16:19

1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.