Difference between value type and reference type in Swift
value type in Swift
In Swift, A value type instance is an independent instance and holds its data in its own memory allocation.
reference type in Swift
In Swift, reference type instances share a single copy of their data, so that every new instance will point to the same address in memory.
value type vs reference type in Swift
| Parameters | value type | reference type |
|---|---|---|
| Type | struct, enum, and tuple | class, functions, and closures |
| Assignment/Passing | Copies data, creates a new instance | Shares the same instance |
| Comparison | Use == for value equality | Use === for identity equality |
| Mutation | Changes don't affect originals | Changes affect all references |
| Use Cases | Simple, independent data | Shared, mutable state, instance identity |