Mobile Development
Swift
Subjective
Oct 04, 2025
Explain the concept of phantom types in Swift.
Detailed Explanation
Phantom types are types that exist only at compile time to provide additional type safety.\n\n• **Basic Concept:**\n\nstruct Tagged {\n let value: Value\n \n init(_ value: Value) {\n self.value = value\n }\n}\n\n// Phantom type tags\nenum UserID {}\nenum ProductID {}\n\ntypealias UserIdentifier = Tagged\ntypealias ProductIdentifier = Tagged\n\n\n• **Usage Example:**\n\nfunc getUser(id: UserIdentifier) -> User? {\n // Implementation\n return nil\n}\n\nfunc getProduct(id: ProductIdentifier) -> Product? {\n // Implementation\n return nil\n}\n\nlet userId = UserIdentifier(123)\nlet productId = ProductIdentifier(456)\n\n// Type safe - correct usage\nlet user = getUser(id: userId)\n\n// Compile error - prevents mixing IDs\n// let user = getUser(id: productId) // ❌ Error\n\n\n• **Advanced Example:**\n\nstruct Distance {\n let value: Double\n \n init(_ value: Double) {\n self.value = value\n }\n}\n\nenum Meters {}\nenum Feet {}\n\ntypealias MetersDistance = Distance\ntypealias FeetDistance = Distance\n\n// Type-safe distance calculations\nfunc convert(_ distance: MetersDistance) -> FeetDistance {\n return FeetDistance(distance.value * 3.28084)\n}\n\n\n• **Benefits:**\n• Compile-time type safety\n• Zero runtime cost\n• Prevents logical errors\n• Self-documenting code\n• API design clarity
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts