I learnt that Swift uses Automatic Reference Counting (ARC) for Memory Management. I want to know how it works for Value Types (struct
) in Swift.
From the Swift Language Guide on ARC:
Reference counting applies only to instances of classes. Structures and enumerations are value types, not reference types, and aren’t stored and passed by reference.
Automatic Reference Counting only applies to reference types because those types are:
This does mean that some system must keep track of when an instance of a type like this (object) is no longer referenced so the allocation can be cleaned up.
In contrast, value types don't have the same concept of identity that objects do:
Value types don't need to be allocated, and don't maintain state that requires cleanup via something like a deinitializer. The net result is that nothing needs to keep track of when a value is last used (since no deallocation is strictly necessary), so no reference counting for cleanup is required.
Advanced note: value types may be allocated on the heap (esp. if they are large enough), but this is an implementation detail of Swift. If a struct
is allocated, Swift itself will maintain the allocation and deallocation on your behalf, while still passing it around transparently by value. It's still not possible to have multiple references to this struct
, so reference counting is still irrelevant for it (e.g. the reference count could only ever be 0 or 1, so it doesn't make sense to track).