It is not possible to say without looking at A.someFunctionA
since it's unknown if completion
is @escaping
(e.g. if it's retained). For the rest of the answer I will assume that it is @escaping
.
Swift needs to ensure runtime safety, and will keep any objects it might need in the future alive, in this case by making a strong reference to self
(since self
is the only variable used inside the closure).
In this scenario there is no reference cycle. This is because instanceA
is not retained, so A => B, but B !=> A.
However, if instanceA
was retained by B
(let's say you create an instanceA: A
property and set it) then you will have a retain cycle.
To get around this you can make variables within the closure either weak
or unowned
. They both do the same thing, but provide you with slightly different types. They both hold a weak reference, meaning that instanceA
will not be increase the reference count of your B
instance; if B
is deallocated and there are no other reference, instanceA
is also deallocated.
When using [weak self]
self
is optional
, e.g. self: B?
. However, [unowned self]
is explicitly unwrapped, e.g. self: B!
. This means that if the closure is called and self
is nil
your program will crash. This is why it's important to only use unowned
when you know for certain that deallocating B
will also deallocate A
. There are a few scenarios where unowned
is safe, e.g. the case when creating a closure and storing it on the same object that created it, but there are more nuances to this.
If unsure, use weak
!