简体   繁体   中英

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
  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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM