Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use [self] vs [weak self] in swift blocks?

Tags:

swift

[self] is new term which we can use in blocks to avoid usage of self keyword. Then how is this different from [weak self]? Does [self] takes cares of retain cycle?

I couldn't find much info on this so any simple example with explanation will be highly appreciated.

like image 981
Vishwanath Deshmukh Avatar asked Oct 23 '20 17:10

Vishwanath Deshmukh


1 Answers

[self] indicates that self is intentionally held with a strong reference (and so some syntax is simplified). [weak self] indicates that self is held with a weak reference.

why would I use strong capture [self] inside block as there are chances of memory leak

You would use this when you know there is no reference cycle, or when you wish there to be a temporary reference cycle. Capturing self does not by itself create a cycle. There has to be a cycle. You may know from your code that there isn't. For example, the thing holding the closure may be held by some other object (rather than self). Good composition (and decomposition of complex types into smaller types) can easily lead to this.

Alternately, you may want a temporary cycle. The most common case of this URLSessionTask. The docs are very valuable here (emphasis added):

After you create a task, you start it by calling its resume() method. The session then maintains a strong reference to the task until the request finishes or fails; you don’t need to maintain a reference to the task unless it’s useful for your app’s internal bookkeeping.

Another common example is DispatchQueue, which similarly holds onto a closure until it finishes. At that point, it releases it, killing the cycle and allowing everything to deallocate. This is useful and powerful (and common!), when used with intent. It's a source of bugs when used accidentally. So Swift requires you to state your intentions and tries to make the situation explicit.

When you build your own types that retain completion handlers, you should strongly consider this pattern, too. After calling the completion handler, set it to nil (or {_ in } for non-optionals) to release anything that completion handler might be referencing.

One frustrating effect of the current situation is that developers slap [weak self] onto closures without thought. That is the opposite of what was intended. Seeing self was supposed to cause developers to pause and think about the reference graph. I'm not certain it ever really achieved this, but as a Swift programmer you should understand that this is the intent. It's not just random syntax.

like image 106
Rob Napier Avatar answered Nov 16 '22 21:11

Rob Napier