Mobile Development Swift Subjective
Oct 04, 2025

How does Swift handle protocol witness tables?

Detailed Explanation
Protocol witness tables enable dynamic dispatch for protocol methods in Swift.\n\n• **Witness Table Structure:**\n\nprotocol Drawable {\n func draw()\n func area() -> Double\n}\n\n// Compiler generates witness table\nstruct CircleWitnessTable { \n let drawFunction: (Circle) -> Void\n let areaFunction: (Circle) -> Double\n}\n\n\n• **Runtime Representation:**\n\n// Existential container\nstruct ProtocolExistential { \n var valueBuffer: (Int64, Int64, Int64) // 24 bytes inline storage\n var type: Any.Type // Type metadata\n var witnessTable: UnsafePointer // Protocol witness table\n}\n\n\n• **Witness Table Generation:**\n\nstruct Circle: Drawable {\n let radius: Double\n \n func draw() {\n print("Drawing circle")\n }\n \n func area() -> Double {\n return .pi * radius * radius\n }\n}\n\n// Compiler generates:\n// CircleDrawableWitnessTable = {\n// draw: Circle.draw,\n// area: Circle.area\n// }\n\n\n• **Performance Implications:**\n• Indirect function calls\n• Cannot be inlined across module boundaries\n• Runtime type checking overhead\n\n• **Optimization Strategies:**\n\n// Specialization for concrete types\nfunc drawShape(_ shape: T) {\n shape.draw() // Can be statically dispatched\n}\n\n// vs existential\nfunc drawShape(_ shape: Drawable) {\n shape.draw() // Dynamic dispatch through witness table\n}\n
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback