Home > OS >  How does Automatic Reference Counting work for Value Types in Swift?
How does Automatic Reference Counting work for Value Types in Swift?

Time:05-09

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.

CodePudding user response:

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:

  1. Always allocated on the heap, because
  2. They must exist in a stable location in memory so that you can be sure that multiple references to the same object are really all pointing to the same exact place (this is part of the concept of identity for objects)

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:

  1. They don't require a stable location in memory, and every copy of a value is indistinguishable from another which has the same properties, so
  2. Every time you refer to a value type, you get a copy of it by value (conceptually; there are optimizations to avoid needless copying all over the place)

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).

  • Related