Printed on: September 18, 2025
As a developer who makes use of Swift usually, [weak self]
must be one thing that is virtually muscle reminiscence to you. I’ve written about utilizing [weak self]
earlier than within the context of when you must usually seize self
weakly in your closures to keep away from retain cycles. The underside line of that submit is that closures that are not @escaping
will often not want a [weak self]
as a result of the closures aren’t retained past the scope of the operate you are passing them to. In different phrases, closures that are not @escaping
do not often trigger reminiscence leaks. I am certain there are exceptions however usually talking I’ve discovered this rule of thumb to carry up.
This concept of not needing [weak self]
for all closures is strengthened by the introduction of SE-0269 which permits us to leverage implicit self
captures in conditions the place closures aren’t retained, making reminiscence leaks unlikely.
Later, I additionally wrote about how Activity
cases that iterate async sequences are pretty more likely to have reminiscence leaks as a result of this implicit utilization of self.
So how will we use [weak self]
on Activity
? And if we should not, how will we keep away from reminiscence leaks?
On this submit, I goal to reply these questions.
The fundamentals of utilizing [weak self]
in completion handlers
As Swift builders, our first intuition is to do a weak -> robust dance in just about each closure. For instance:
loadData { [weak self] information in
guard let self else { return }
// use information
}
This method makes loads of sense. We begin the decision to loadData
, and as soon as the info is loaded our closure known as. As a result of we need not run the closure if self
has been deallocated throughout our loadData
name, we use guard let self
to ensure self
remains to be there earlier than we proceed.
This turns into more and more necessary once we stack work:
loadData { [weak self] information in
guard let self else { return }
processData(information) { [weak self] fashions in
// use fashions
}
}
Discover that we use [weak self]
in each closures. As soon as we seize self
with guard let self
our reference is robust once more. Which means that for the remainder of our closure, self
is held on to as a robust reference. Resulting from SE-0269
we are able to name processData
with out writing self.processData
if we have now a robust reference to self.
The closure we go to processData
additionally captures self
weakly. That is as a result of we do not need that closure to seize our robust reference. We want a brand new [weak self]
to stop the closure that we handed to processData
from making a (shortly lived) reminiscence leak.
Once we take all this data and we switch it to Activity
, issues get fascinating…
Utilizing [weak self]
and unwrapping it instantly in a Activity
To illustrate that we wish to write an equal of our loadData
and processData
chain, however they’re now async
features that do not take a completion handler.
A standard first method can be to do the next:
Activity { [weak self] in
guard let self else { return }
let information = await loadData()
let fashions = await processData(information)
}
Sadly, this code doesn’t resolve the reminiscence leak that we solved in our authentic instance.
An unstructured Activity
you create will begin operating as quickly as potential. Which means that if we have now a operate like under, the duty will run as quickly because the operate reaches the top of its physique:
func loadModels() {
// 1
Activity { [weak self] in
// 3: _immediately_ after the operate ends
guard let self else { return }
let information = await loadData()
let fashions = await processData(information)
}
// 2
}
Extra advanced name stacks may push the beginning of our activity again by a bit, however usually talking, the duty will run just about instantly.
The issue with guard let self
initially of your Activity
As a result of Activity
in Swift begins operating as quickly as potential, the prospect of self
getting deallocated within the time between creating and beginning the duty is very small. It is not inconceivable, however by the point your Activity
begins, it is possible self
remains to be round it doesn’t matter what.
After we make our reference to self
robust, the Activity
holds on to self
till the Activity
completes. In our name that implies that we retain self
till our name to processData
completes. If we translate this again to our outdated code, here is what the equal would seem like in callback primarily based code:
loadData { information in
self.processData(information) { fashions in
// for instance, self.useModels
}
}
We do not have [weak self]
wherever. Which means that self
is retained till the closure we go to processData
has run.
The very same factor is occurring in our Activity
above.
Usually talking, this is not an issue. Your work will end and self
is launched. Possibly it sticks round a bit longer than you need nevertheless it’s not an enormous deal within the grand scheme of issues.
However how would we forestall kicking off processData
if self
has been deallocated on this case?
Stopping a robust self within your Activity
We might guarantee that we by no means make our reference to self
into a robust one. For instance, by checking if self
remains to be round by way of a nil
examine or by guarding the results of processData
. I am utilizing each strategies within the snippet above however the guard self != nil
could possibly be omitted on this case:
Activity { [weak self] in
let information = await loadData()
guard self != nil else { return }
guard let fashions = await self?.processData(information) else {
return
}
// use fashions
}
The code is not fairly, however it might obtain our aim.
Let’s check out a barely extra advanced subject that includes repeatedly fetching information in an unstructured Activity
.
Utilizing [weak self]
in an extended operating Activity
Our authentic instance featured two async calls that, primarily based on their names, most likely would not take all that lengthy to finish. In different phrases, we have been fixing a reminiscence leak that will sometimes resolve itself inside a matter of seconds and you could possibly argue that is not truly a reminiscence leak price fixing.
A extra advanced and fascinating instance might look as follows:
func loadAllPages() {
// solely fetch pages as soon as
guard fetchPagesTask == nil else { return }
fetchPagesTask = Activity { [weak self] in
guard let self else { return }
var hasMorePages = true
whereas hasMorePages && !Activity.isCancelled {
let web page = await fetchNextPage()
hasMorePages = !web page.isLastPage
}
// we're finished, we might name loadAllPages once more to restart the loading course of
fetchPagesTask = nil
}
}
Let’s take away some noise from this operate so we are able to see the bits which can be truly related as to if or not we have now a reminiscence leak. I wished to indicate you the total instance that can assist you perceive the larger image of this code pattern…
Activity { [weak self] in
guard let self else { return }
var hasMorePages = true
whereas hasMorePages {
let web page = await fetchNextPage()
hasMorePages = !web page.isLastPage
}
}
There. That is a lot simpler to take a look at, is not it?
So in our Activity
we have now a [weak self]
seize and instantly we unwrap with a guard self
. You already know this may not do what we would like it to. The Activity
will begin operating instantly, and self
shall be held on to strongly till our activity ends. That stated, we do need our Activity
to finish if self
is deallocated.
To attain this, we are able to truly transfer our guard let self
into the whereas
loop:
Activity { [weak self] in
var hasMorePages = true
whereas hasMorePages {
guard let self else { break }
let web page = await fetchNextPage()
hasMorePages = !web page.isLastPage
}
}
Now, each iteration of the whereas loop will get its personal robust self
that is launched on the finish of the iteration. The following one makes an attempt to seize its personal robust copy. If that fails as a result of self
is now gone, we escape of the loop.
We mounted our drawback by capturing a robust reference to self
solely once we want it, and by making it as short-lived as potential.
In Abstract
Most Activity
closures in Swift do not strictly want [weak self]
as a result of the Activity
usually solely exists for a comparatively quick period of time. For those who discover that you just do wish to guarantee that the Activity
would not trigger reminiscence leaks, you must guarantee that the primary line in your Activity
is not guard let self else { return }
. If that is the primary line in your Activity
, you are capturing a robust reference to self
as quickly because the Activity
begins operating which often is sort of instantly.
As a substitute, unwrap self
solely whenever you want it and ensure you solely preserve the unwrapped self
round as quick as potential (for instance in a loop’s physique). You can additionally use self?
to keep away from unwrapping altogether, that method you by no means seize a robust reference to self
. Lastly, you could possibly take into account not capturing self
in any respect. For those who can, seize solely the properties you want in order that you do not depend on all of self
to stay round whenever you solely want elements of self
.