robdashnash robdashnash - 5 months ago 35x
Swift Question

Objective-C __strong equivalent in Swift

In Objective-C we cast values as __weak to avoid retain cycles in certain situations.

This post explains why __strong is useful

__weak typeof (self) weakSelf = self;

self.block = ^{
[weakSelf methodA];

Do we specifically need a __strong self equivalent in Swift and is it available ? If so, what is the syntax please ?


There is nothing like __strong in Swift because all variables are strong by default.

Below is the Swift equivalent of the above code:

self.block = { [weak self] in

If you want to keep self alive during the execution of the block, you can do something like below:

self.block = { [weak self] in
  guard let strongSelf = self else { return }

In the above code, strongSelf will create a strong reference to weakSelf inside the block so that the weak reference won't get deallocated while strong one is alive (which in our case until the block finishes executing).

Please note that none of the options above will cause retain cycles.