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

weak

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

Unowned

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 🤨

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store