Why is the new
keyword not necessary in Swift?
In other languages such as Java or C#, new
is necessary to allocate memory for a each new object. Ex.
(Foo) foo = new Foo()
However in swift, it's
(var) foo = Foo()
If Swift has built in garbage collection/memory allocation, is new
implicit, or is it simply not used. If the latter, why/what replaces it?
For heap-allocated/reference types (class
es), Swift utilizes Automatic Reference Counting: rather than requiring explicit calls to delete
, memory is deallocated when the last "strong" reference to it disappears. var foo = Foo()
or let foo = Foo()
allocates and initializes an instance of the Foo
class, and creates a local variable with a strong reference to it. When this variable goes out of scope, if no other references have been made, the object is deallocated.
From The Swift Programming Language:
Every time you create a new instance of a class, ARC allocates a chunk of memory to store information about that instance. This memory holds information about the type of the instance, together with the values of any stored properties associated with that instance.
Additionally, when an instance is no longer needed, ARC frees up the memory used by that instance so that the memory can be used for other purposes instead. This ensures that class instances do not take up space in memory when they are no longer needed.
You can also read about the initialization sequence, i.e. the interactions between properties and custom init
s in a class hierarchy.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments