質問

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?

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません softwareengineering.stackexchange
scroll top