Traditionally in Objc, we do weakSelf to prevent additional retain count for blocks.
How does swift internally manage retain cycles that occur in blocks for Objc?
As described above there are 2 possibilities to avoid retain cycles in Swift and these are weak and unowned as described below:
var sampleClosure = { [unowned self] in
self.doSomething()
}
where the self never can be nil.
var sampleClosure = { [weak self] in
self?.doSomething()
}
where self need to be unwrapped using ?.
Here there is a important observation to do, if there are more instructions that use self and can be share the results etc, a possible correct way can be:
var sampleClosure = { [weak self] in
if let this = self{
this.doSomething()
this.doOtherThings()
}
}
or
var sampleClosure = { [weak self] in
guard let strongSelf = self else{
return
}
strongSelf.doSomething()
strongSelf.doOtherThings()
}