DevPrep

All topics › Modern Swift

Witness table vs vtable — what's the difference?

Senior PRO

The idea

Both are tables of function pointers through which table dispatch goes, but they answer different questions:

protocol Shape { func area() -> Double }
struct Circle: Shape {
    let r: Double
    func area() -> Double { .pi * r * r }
}
class Animal { func sound() -> String { "..." } }
class Dog: Animal { override func sound() -> String { "Woof" } }

func areaGeneric<S: Shape>(_ s: S) -> Double { s.area() }
func areaExistential(_ s: any Shape) -> Double { s.area() }

let pet: Animal = Dog()
_ = pet.sound()                        // Dog's vtable
_ = areaGeneric(Circle(r: 1))          // witness table (or specialization)
_ = areaExistential(Circle(r: 1))      // existential → witness table

The rest of this answer, with code and interview follow-ups, is in the DevPrep app.

Read the full answer in DevPrep

Practice this before your interview

DevPrep turns these answers into one-minute challenges: what does this code print, find the bug, mock interviews. One challenge a day.

Get DevPrep on the App Store