Revealed on: September 18, 2025
As a developer who makes use of Swift often, [weak self]
needs to be one thing that is nearly muscle reminiscence to you. I’ve written about utilizing [weak self]
earlier than within the context of when it is best to typically 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 normally not want a [weak self]
as a result of the closures aren’t retained past the scope of the perform you are passing them to. In different phrases, closures that are not @escaping
do not normally trigger reminiscence leaks. I am certain there are exceptions however typically talking I’ve discovered this rule of thumb to carry up.
This concept of not needing [weak self]
for all closures is bolstered 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 resulting from this implicit utilization of self.
So how can we use [weak self]
on Activity
? And if we should not, how can we keep away from reminiscence leaks?
On this submit, I purpose 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] knowledge in
guard let self else { return }
// use knowledge
}
This method makes loads of sense. We begin the decision to loadData
, and as soon as the information is loaded our closure is known as. As a result of we needn’t 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 essential after we stack work:
loadData { [weak self] knowledge in
guard let self else { return }
processData(knowledge) { [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 powerful once more. Which means for the remainder of our closure, self
is held on to as a powerful reference. Resulting from SE-0269
we will name processData
with out writing self.processData
if we’ve a powerful reference to self.
The closure we move to processData
additionally captures self
weakly. That is as a result of we do not need that closure to seize our robust reference. We’d like a brand new [weak self]
to forestall the closure that we handed to processData
from making a (shortly lived) reminiscence leak.
After we take all this data and we switch it to Activity
, issues get attention-grabbing…
Utilizing [weak self]
and unwrapping it instantly in a Activity
As an example that we need to write an equal of our loadData
and processData
chain, however they’re now async
features that do not take a completion handler.
A typical first method can be to do the next:
Activity { [weak self] in
guard let self else { return }
let knowledge = await loadData()
let fashions = await processData(knowledge)
}
Sadly, this code doesn’t remedy the reminiscence leak that we solved in our authentic instance.
An unstructured Activity
you create will begin working as quickly as attainable. Which means if we’ve a perform like beneath, the duty will run as quickly because the perform reaches the tip of its physique:
func loadModels() {
// 1
Activity { [weak self] in
// 3: _immediately_ after the perform ends
guard let self else { return }
let knowledge = await loadData()
let fashions = await processData(knowledge)
}
// 2
}
Extra advanced name stacks would possibly push the beginning of our activity again by a bit, however typically 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 working as quickly as attainable, the possibility of self
getting deallocated within the time between creating and beginning the duty is very small. It isn’t not possible, 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 previous code, here is what the equal would seem like in callback based mostly code:
loadData { knowledge in
self.processData(knowledge) { fashions in
// for instance, self.useModels
}
}
We do not have [weak self]
wherever. Which means self
is retained till the closure we move to processData
has run.
The very same factor is going on in our Activity
above.
Usually talking, this is not an issue. Your work will end and self
is launched. Perhaps it sticks round a bit longer than you need however it’s not a giant deal within the grand scheme of issues.
However how would we stop kicking off processData
if self
has been deallocated on this case?
Stopping a powerful self within your Activity
We might guarantee that we by no means make our reference to self
into a powerful one. For instance, by checking if self
remains to be round by way of a nil
test or by guarding the results of processData
. I am utilizing each methods within the snippet above however the guard self != nil
may very well be omitted on this case:
Activity { [weak self] in
let knowledge = await loadData()
guard self != nil else { return }
guard let fashions = await self?.processData(knowledge) else {
return
}
// use fashions
}
The code is not fairly, however it could obtain our purpose.
Let’s check out a barely extra advanced difficulty that includes repeatedly fetching knowledge in an unstructured Activity
.
Utilizing [weak self]
in an extended working Activity
Our authentic instance featured two async calls that, based mostly on their names, in all probability would not take all that lengthy to finish. In different phrases, we have been fixing a reminiscence leak that will sometimes remedy itself inside a matter of seconds and you can argue that is not truly a reminiscence leak price fixing.
A extra advanced and attention-grabbing 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 carried out, we might name loadAllPages once more to restart the loading course of
fetchPagesTask = nil
}
}
Let’s take away some noise from this perform so we will see the bits which might be truly related as to if or not we’ve a reminiscence leak. I needed to point out 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’ve a [weak self]
seize and instantly we unwrap with a guard self
. You already know this may not do what we wish it to. The Activity
will begin working instantly, and self
can be held on to strongly till our activity ends. That mentioned, we do need our Activity
to finish if self
is deallocated.
To attain this, we will 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 subsequent 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 fastened our downside by capturing a powerful reference to self
solely after we want it, and by making it as short-lived as attainable.
In Abstract
Most Activity
closures in Swift do not strictly want [weak self]
as a result of the Activity
typically solely exists for a comparatively quick period of time. When you discover that you simply do need to guarantee that the Activity
does not trigger reminiscence leaks, it is best to 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 powerful reference to self
as quickly because the Activity
begins working which normally is sort of instantly.
As a substitute, unwrap self
solely whenever you want it and be sure you solely preserve the unwrapped self
round as quick as attainable (for instance in a loop’s physique). You would additionally use self?
to keep away from unwrapping altogether, that method you by no means seize a powerful reference to self
. Lastly, you can take into account not capturing self
in any respect. When you 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 components of self
.