Mobile Development
Swift
Subjective
Oct 04, 2025
What is the difference between structural and nominal typing?
Detailed Explanation
Swift uses nominal typing with some structural elements, affecting type relationships.\n\n• **Nominal Typing:**\n• Types identified by name/declaration\n• Explicit conformance required\n• Swift's primary approach\n\n\nstruct Point {
\n let x: Double\n let y: Double\n}\n\nstruct Vector {
\n let x: Double\n let y: Double\n}\n\n// Different types despite same structure\nlet point = Point(x: 1, y: 2)\nlet vector = Vector(x: 1, y: 2)\n// point = vector // ❌ Error - different nominal types\n\n\n• **Structural Elements:**\n• Function types are structural\n• Tuple types are structural\n• Closure compatibility\n\n\n// Function types are structural\ntypealias BinaryOperation = (Int, Int) -> Int\ntypealias Calculator = (Int, Int) -> Int\n\nlet add: BinaryOperation = { $0 + $1 }\nlet calc: Calculator = add // ✅ Compatible - same structure\n\n// Tuple compatibility\nlet tuple1: (Int, String) = (1, "hello")\nlet tuple2: (Int, String) = tuple1 // ✅ Same structure\n\n\n• **Protocol Conformance:**\n\nprotocol Equatable {\n static func == (lhs: Self, rhs: Self) -> Bool\n}\n\n// Explicit conformance required (nominal)\nstruct Person: Equatable {\n let name: String\n \n static func == (lhs: Person, rhs: Person) -> Bool {\n return lhs.name == rhs.name\n }\n}\n\n\n• **Benefits of Nominal Typing:**\n• Clear type relationships\n• Explicit intent\n• Better error messages\n• Prevents accidental compatibility
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts