WeakSelf done right in Swift

Hi CodeBugs,

A long time ago we discovered that objective C blocks capture strong pointers to any object referenced inside their body. In order to avoid retain cycles we did this:

id __weak weakSelf = self  
[self doSomethingWithCompletionBlock: ^{
    [weakSelf updateUI];
}];

In Swift we can(and should) use capture lists to achieve the same behaviour:

self.doSomethingWithCompletionBlock {[weak self, weak delegate = self.delegate!] in  
    self.updateUI()
    delegate.doSomething()
}

So what is the official definition of a capture list?

A capture list is written as a comma separated list of expressions surrounded by square brackets, before the list of parameters. If you use a capture list, you must also use the in keyword, even if you omit the parameter names, parameter types, and return type.

Capture lists are the better, native solution to the problem, so code like the following has no reason to exist:

weak var weakSelf = self  
self.doSomethingWithCompletionBlock {  
    weakSelf.updateUI()
}

The Code Bug

A passionate iOS developer. Looking to radically improve the way we all develop software.

Amsterdam