Tometoyou
Tometoyou

Reputation: 8386

Should I use [weak self] if I don't actually reference self in my completion block?

I use [weak self] when I have a completion block that refers to properties of my class object. However, sometimes I have a completion block that doesn't refer to any properties, but the class object could disappear and deinit. Should I be using [weak self] or not? It usually gives a warning Variable 'self' was written to, but never read when I do...

doSomeFunction() { [weak self] in
   // No references to self here
}

Upvotes: 11

Views: 5655

Answers (3)

user9335240
user9335240

Reputation: 1799

Capturing the variables, happens only when you use it internally, a closure will NEVER capture the variables by default (not like Java inner class which ALWAYS captures this), so, it you use a variable (including self) inside the closure, it is captured.

Also you can manually capture the variables using the [weak self], [weak your_variable_here], [unowned self], [unowned your_variable_here], [self] or [your_variable_here]

If the compiler tells you variable "self" is written to but never read from, it means that you didn't use self inside, so it is completely safe not to use [weak self], because self will NOT be captured, because it is not used.

weak self or unowned self is needed only when your closure captures self, and escapes the function it is passed to, especially if it is saved in a variable.

Refer to Closures in Apple's Official Swift Documentation

Upvotes: 18

Daniel Hall
Daniel Hall

Reputation: 13679

There are two scenarios when it is correct / appropriate to use [weak self] in closures:

1) The closure references self and is also itself is somehow retained by self, or retained by an object that is in turn retained by self (circular reference / retain cycle).

2) The closure references self, has no form of circular reference with self, but the intent is for the closure NOT to prevent self from being released if there are no other references to self.

In all other cases, there is no need to use [weak self], including cases where the closure has no reference to self (or instance members of self).

Upvotes: 0

Murf
Murf

Reputation: 1719

No you don't need to. Swift won't do anything with the reference that isn't used so NOT using it does the same as using it.

Upvotes: 1

Related Questions