Okay so we all know that in traditional concurrency in Swift, if you are performing (for example) a network request inside a class, and in the completion of that request you reference a function that belongs to that class, you must pass [weak self]
in, like this:
func performRequest() {
apiClient.performRequest { [weak self] result in
self?.handleResult(result)
}
}
This is to stop us strongly capturing self
in the closure and causing unnecessary retention/inadvertently referencing other entities that have dropped out of memory already.
How about in async/await? I’m seeing conflicting things online so I’m just going to post two examples to the community and see what you think about both:
class AsyncClass {
func function1() async {
let result = await performNetworkRequestAsync()
self.printSomething()
}
func function2() {
Task { [weak self] in
let result = await performNetworkRequestAsync()
self?.printSomething()
}
}
func function3() {
apiClient.performRequest { [weak self] result in
self?.printSomething()
}
}
func printSomething() {
print("Something")
}
}
function3
is straightforward – old fashioned concurrency means using [weak self]
.
function2
I think is right, because we’re still capturing things in a closure so we should use [weak self]
.
function1
is this just handled by Swift, or should I be doing something special here?
2
Answers
This isn’t quite true. When you create a closure in Swift, the variables that the closure references, or "closes over", are retained by default, to ensure that those objects are valid to use when the closure is called. This includes
self
, whenself
is referenced inside of the closure.The typical retain cycle that you want to avoid requires two things:
self
, andself
retains the closure backThe retain cycle happens if
self
holds on to the closure strongly, and the closure holds on toself
strongly — by default ARC rules with no further intervention, neither object can be released (because something has retained it), so the memory will never be freed.There are two ways to break this cycle:
Explicitly break a link between the closure and
self
when you’re done calling the closure, e.g. ifself.action
is a closure which referencesself
, assignnil
toself.action
once it’s called, e.g.This isn’t usually applicable because it makes
self.action
one-shot, and you also have a retain cycle until you callself.action()
. Alternatively,Have either object not retain the other. Typically, this is done by deciding which object is the owner of the other in a parent-child relationship, and typically,
self
ends up retaining the closure strongly, while the closure referencesself
weakly viaweak self
, to avoid retaining itThese rules are true regardless of what
self
is, and what the closure does: whether network calls, animation callbacks, etc.With your original code, you only actually have a retain cycle if
apiClient
is a member ofself
, and holds on to the closure for the duration of the network request:If the closure is actually dispatched elsewhere (e.g.,
apiClient
does not retain the closure directly), then you don’t actually need[weak self]
, because there was never a cycle to begin with!The rules are exactly the same with Swift concurrency and
Task
:Task
to initialize it with retains the objects it references by default (unless you use[weak ...]
)Task
holds on to the closure for the duration of the task (i.e., while it’s executing)self
holds on to theTask
for the duration of the executionIn the case of
function2()
, theTask
is spun up and dispatched asynchronously, butself
does not hold on to the resultingTask
object, which means that there’s no need for[weak self]
. If instead,function2()
stored the createdTask
, then you would have a potential retain cycle which you’d need to break up:If you need to hold on to the task (e.g. so you can
cancel
it), you’ll want to avoid having the task retainself
back (Task { [weak self] ... }
).Bottom line, there is often little point in using
[weak self]
capture lists withTask
objects. Use cancelation patterns instead.A few detailed considerations:
Weak capture lists are not required.
You said:
This is not true. Yes, it may be prudent or advisable to use the
[weak self]
capture list, but it is not required. The only time you “must” use aweak
reference toself
is when there is a persistent strong reference cycle.For well-written asynchronous patterns (where the called routine releases the closure as soon as it is done with it), there is no persistent strong reference cycle risk. The
[weak self]
is not required.Nonetheless, weak capture lists are useful.
Using
[weak self]
in these traditional escaping closure patterns still has utility. Specifically, in the absence of theweak
reference toself
, the closure will keep a strong reference toself
until the asynchronous process finishes.A common example is when you initiate a network request to show some information in a scene. If you dismiss the scene while some asynchronous network request is in progress, there is no point in keeping the view controller in memory, waiting for a network request that merely updates the associated views that are long gone.
Needless to say, the
weak
reference toself
is really only part of the solution. If there’s no point in retainingself
to wait for the result of the asynchronous call, there is often no point in having the asynchronous call continue, either. E.g., we might marry aweak
reference toself
with adeinit
that cancels the pending asynchronous process.Weak capture lists are less useful in Swift concurrency.
Consider this permutation of your
function2
:This looks like it should not keep a strong reference to
self
whileperformNetworkRequestAsync
is in progress. But the reference to a property,apiClient
, will introduce a strong reference, without any warning or error message. E.g., below, I letAsyncClass
fall out of scope at the red signpost, but despite the[weak self]
capture list, it was not released until the asynchronous process finished:The
[weak self]
capture list accomplishes very little in this case. Remember that in Swift concurrency there is a lot going on behind the scenes (e.g., code after the “suspension point” is a “continuation”, etc.). It is not the same as a simple GCD dispatch. See Swift concurrency: Behind the scenes.If, however, you make all property references
weak
, too, then it will work as expected:Hopefully, future compiler versions will warn us of this hidden strong reference to
self
.Make tasks cancelable.
Rather than worrying about whether you should use
weak
reference toself
, one could consider simply supporting cancelation:And then,
Now, obviously, that assumes that your task supports cancelation. Most of the Apple async API does. (But if you have written your own
withUnsafeContinuation
-style implementation, then you will want to periodically checkTask.isCancelled
or wrap your call in awithTaskCancellationHandler
or other similar mechanism to add cancelation support. But this is beyond the scope of this question.)