In Swift, both classes and structures are used to define custom data types — but they have different behaviors, especially in memory management, inheritance, and value/reference semantics.
Basic Definitions of Classes and Structures in Swift
Structure (struct)
- Value type: copied when assigned or passed.
- Stored in the stack (usually, if small/simple).
- Preferred for small, lightweight models.
struct Person { var name: String
}
Class
- Reference type: passed by reference.
- Stored in the heap.
- Supports inheritance, deinitializers, and identity checks.
class Person { var name: String
}
Key Differences Between Struct vs Class in iOS
Feature | Struct | Class |
Type | Value type | Reference type |
Copy behavior | Copies on assignment | Shares the same instance |
Inheritance | Not supported | Supported |
Deinitializer | Not allowed | deinit available |
Identity (===) check | Not applicable | Can check reference identity |
Storage | Stack (small data) | Heap |
Value vs Reference Behavior
1. Struct (Value Type)
struct User { var name: String
}
var user1 = User(name: "Alice")
var user2 = user1
user2.name = "Bob"
print(user1.name) // "Alice"
print(user2.name) // "Bob"
Changing user2 doesn’t affect user1 because structs are copied.
2. Class (Reference Type)
class User { var name: String init(name: String) { self.name = name }
}
var user1 = User(name: "Alice")
var user2 = user1
user2.name = "Bob"
print(user1.name) // "Bob"
print(user2.name) // "Bob"
Both user1 and user2 point to the same object in memory.
Conclusion
Use structs when you need simple, independent copies of data. Use classes when you need shared references, inheritance, or lifecycle control. For best architecture decisions in your app, consider hiring an iOS developer who understands when to use each effectively.