Mobile Development
Swift
Subjective
Oct 04, 2025
Explain the difference between classes and structures in Swift.
Detailed Explanation
Classes and structures are fundamental building blocks in Swift with key differences.\n\n• **Classes (Reference Types):**\n• Passed by reference\n• Support inheritance\n• Can have deinitializers\n• Reference counting applies\n• Identity operators (=== and !==)\n• Can be changed even when declared with let\n\n• **Structures (Value Types):**\n• Passed by value (copied)\n• No inheritance support\n• No deinitializers\n• Automatic memberwise initializers\n• Cannot be changed when declared with let\n• Copy-on-write optimization\n\n**Examples:**\n\nclass PersonClass {
\n var name: String\n init(name: String) { self.name = name }\n}\n\nstruct PersonStruct {
\n var name: String\n}\n\nlet classInstance = PersonClass(name: "John")\nclassInstance.name = "Jane" // ✅ Allowed\n\nlet structInstance = PersonStruct(name: "John")\n// structInstance.name = "Jane" // ❌ Error\n
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts