Functional programming: Closure reference cycle and fix

Here, I will try to explain an example of closure reference cycle. Follow the following article to understand more about closures in swift.

The reference cycle looks rusty !!!
closure reference cycle.
var humanObj:Human? = Human(firstName: “John”, lastName: “Doe”)let fullName = humanObj?.fullNamehumanObj = nil

The fix


lazy var fullName:() -> String = { [weak self] inguard let weakSelf = self else { return “”}return “\(weakSelf.firstName) \(weakSelf.lastName)”}


lazy var fullName:() -> String = { [unowned self] inreturn “\(self.firstName) \(self.lastName)”}
lazy var fullName:() -> String = { [unowned unownedSelf = self] inreturn “\(unownedSelf.firstName) \(unownedSelf.lastName)”}

How to capture self with closures having arguments?

capturing self along with closure parameters

Exceptional cases:

DispatchQueue.main.async {
self.doSomething() // Not a retain cycle
UIView.animate(withDuration: 1) {
self.doSomething() // Not a retain cycle
lazy var fullName = {
return self.firstName + " " + self.lastName
}() // not retained. no need to use self with weak or unowned

If you enjoyed reading this post, please share and recommend it so others can find it 💚💚💚💚💚💚 !!!!

iOS and tvOS developer, dreamer, photographer 🤨