Most developers ask frequently why so many times the weak keyword is used before some variable declarations such as delegates, outlets and other optionals. There is also this unowned keyword which is used with reference types that are not optionals. There is one single concept in Swift that solves this puzzle called ARC
ARC: Checking your pointers existence
ARC stands for Automatic Reference Counting and is one of the most important mechanisms in the Swift Language made to prevent memory leaks. ARC has a counter for each reference to a memory address and every time you declare a new variable referencing some address, this address's counter is incremented by one. Check an example:
Notice that v3 references the same address as v1, so the count for it stands for 2, while address2 is being pointed only by one variable
Memory leaks occur when some memory space is allocated for some use during the application and suddenly it cannot be accessed anymore while it still exists during the lifecycle. The problem is that as long as we cannot access this piece of memory anymore, it cannot be deallocated unless the application is stopped, becoming just a piece of junk in the app. If you as a developer don't take care with those leaks, the big amount of wasted memory may crash your app bringing problems to your users. Take a look at the following scenario for better understanding:
What do you think it happens in this scenario? When you free a's memory space, the reference to b's memory space that was in a still exists, the same when you free b's reference. After this, you don't have any other variable you can access that points to a and b addresses but ARC still counts those two references.
Memory leak solved
To solve that memory leak issue, we need a way to tell ARC that we don't want some specific references to be count. It's time for weak references.
When you define a reference as weak, you are telling ARC that you don't want that reference to be count, so, ARC will only consider the strong references. In our example, if MyClassB reference MyClassA as a weak pointer, when a and b are set to nil, ARC will see that a's reference at MyClassB instance is not counted, so it will free a's memory space, which will also imply in b's memory space deallocation. Take a look bellow:
When you have two instances that reference themselves, one of them must be declared as weak to guarantee we won't face memory leaks.
How about unowned variables?
Like the weak variables, the unowned ones are not counted by the ARC, but different from the first type, they are not optionals. Usually, the unowned properties work as an object that the other which references it depends to have some meaning. A good example is a credit card:
In this article we took a look on the true meaning of the weak and unowned modifiers and explained how memory leaks can be avoided in an iOS application. Hope you enjoyed ;)