Mobile Development
Swift
Subjective
Oct 04, 2025
Explain the concept of existential types in Swift.
Detailed Explanation
Existential types represent "any type that conforms to a protocol" in Swift.\n\n• **Basic Concept:**\n\nprotocol Drawable {\n func draw()\n}\n\n// Existential type\nvar drawable: Drawable = Circle() // or Rectangle(), etc.\ndrawable.draw() // Dynamic dispatch\n\n\n• **Existential Containers:**\n• Store value and type metadata\n• Witness table for protocol methods\n• Value buffer for inline storage\n\n\n// Internal representation\nstruct ExistentialContainer {
\n var valueBuffer: (Int, Int, Int) // Inline storage\n var type: Any.Type // Type metadata\n var witnessTable: UnsafePointer // Protocol witness table\n}\n\n\n• **Performance Implications:**\n• Dynamic dispatch overhead\n• Potential heap allocation\n• Copy semantics for value types\n\n• **Any vs AnyObject:**\n\n// Any: can hold any type\nvar anything: Any = 42\nanything = "String"\nanything = [1, 2, 3]\n\n// AnyObject: only reference types\nvar anyObject: AnyObject = NSString("Hello")\n// anyObject = 42 // ❌ Error\n\n\n• **Type Erasure Pattern:**\n\nstruct AnySequence: Sequence {\n let _makeIterator: () -> AnyIterator\n \n init(_ sequence: S) where S.Element == Element {\n _makeIterator = { AnyIterator(sequence.makeIterator()) }\n }\n \n func makeIterator() -> AnyIterator {\n return _makeIterator()\n }\n}\n
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts