Search code examples
swiftmemory-managementstructureautomatic-ref-countingvalue-type

ARC doesn't apply to struct and enum, how are they deallocated in Swift


Since ARC doesn't apply to struct and enum, then how are they deallocated from the memory? I have to get stuck when it asked in the interviews and try to find the correct answer but can't find much info on it googling. I know swift is smart at handling value types. But how?


Solution

  • The memory management of objects (instances of classes) is relatively difficult, because objects can outlive a function call, the life of other objects, or even the life of the threads that allocated them. They're independent entities on the heap, that need book keeping to make sure they're freed once they're not needed (once they're no longer referenced from any other threads/objects, they're unreachable, thus can't possible be needed, so are safe to delete).

    On the other hand, structs and enums just have their instances stored inline:

    • If they're declared as a global variable, they're stored in the program text.
    • If they're declared as a local variable, they're allocated on the stack (or in registers, but never mind that).
    • If they're allocated as a property of another object, they're just stored directly inline within that object.

    They're only ever deleted by virtue of their containing context being deallocated, such as when a function returns, or when an object is deallocated.