How is memory management for reference types handled in Swift?
sobes.tech AI
Answer from AI
In Swift, memory management for reference types (classes) is handled using Automatic Reference Counting (ARC). Each object in the heap maintains a reference count — the number of active references to that object. When a new reference to an object is created, the count increases, and when a reference is no longer used, the count decreases. When the count reaches zero, the object is automatically removed from memory.
Example:
class Person {
var name: String
init(name: String) {
self.name = name
}
}
var a: Person? = Person(name: "Alice") // reference count = 1
var b = a // reference count = 2
b = nil // reference count = 1
a = nil // reference count = 0, object is deleted
It is important to avoid retain cycles, where two objects hold strong references to each other, preventing memory from being released. To prevent this, weak and unowned references are used.
Value types (structures, enumerations) are stored on the stack and copied upon assignment, so ARC does not apply to them.