Swift Strong and Weak References
In Swift, ARC (Automatic Reference Counting) automatically handles the allocation and deallocation of memory.
However, we can prevent ARC to automatically dellocate memory by specifying the type of reference.
For example,
A strong reference keeps a firm hold on instances and doesn’t allow deallocation by ARC.
Similarly, A weak reference cannot protect the instances from being deallocated by ARC.
Note: The declaration of a property is strong by default. To declare a weak reference we use the weak
keyword.
Strong Reference in Swift
In Swift, whenever we create an instance of a class, a reference count value is increased from 0 to 1. Similarly, if we dellocate the instance the count is decreased to 0.
Swift Weak Reference
As mentioned earlier, a weak reference doesn’t protect the object from being deallocated. This is because when we declare a property as weak, the reference count of that property will never be more than 1.
class Employee {
weak var colleague: Employee?
...
}