0

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 ?

Community
  • 1
  • 1
  • 1
    Possible duplicate of [How to Correctly handle Weak Self in Swift Blocks with Arguments](http://stackoverflow.com/questions/24468336/how-to-correctly-handle-weak-self-in-swift-blocks-with-arguments) – Ozgur Vatansever May 18 '16 at 17:58
  • `__strong` is the default for variables and ivars in both Obj-C and Swift. I think the only reason Obj-C has that keyword is consistency. You don't need to write it explicitly. – hamstergene May 18 '16 at 19:37

1 Answers1

1

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
  self?.methodA()
}

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 }
  strongSelf.methodA()
}

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.

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • Is it fair to say that the strongSelf reference that holds on to the weakSelf reference, causes a transient retain cycle ? Once the block finishes executing the retain cycle is broken. What you think ? –  May 19 '16 at 09:08
  • Yes, it is safe to say that the block holds a strong reference so there is a transient cycle there which keeps self alive. But the main point is that it shouldn't lead to a some sort of deadlock which causes self to never get deallocated. Using weak keyword ensures that to never happen by creating a strong reference to a weak pointer. – Ozgur Vatansever May 20 '16 at 00:53
  • Thanks for getting back to me. –  May 20 '16 at 09:00