Skip to content

Instantly share code, notes, and snippets.

@juliancadi
Last active March 10, 2021 23:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliancadi/5daf684cbf785191ce1e0c7960996566 to your computer and use it in GitHub Desktop.
Save juliancadi/5daf684cbf785191ce1e0c7960996566 to your computer and use it in GitHub Desktop.
Nested closures
import Foundation
class Closureception {
deinit {
print("⚠️ Deallocated")
}
// MARK: - Cases
func retainCycle() {
self.outer { [weak self] in
guard let self = self else { return print("πŸ‘½ self already deallocated, sorry, ciao") }
print(self.sayHi(to: "Julian"))
self.inner(name: "Alex") {
print("πŸ‘» Retaining self strongly. And you call yourself iOS developer?...")
print(self.sayHi(to: $0))
}
}
}
func rightWay() {
self.outer { [weak self] in
guard let self = self else { return print("πŸ‘½ self already deallocated, sorry, ciao") }
print(self.sayHi(to: "Julian"))
self.inner(name: "Alex") { [weak self] in
guard let self = self else { return print("☠️ self deallocated ages ago, go away!") }
print(self.sayHi(to: $0))
}
}
}
// MARK: - Helpers
private func outer(closure: @escaping () -> Void) { closure() }
private func inner(name: String, closure: @escaping (String) -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { closure(name) }
}
private func sayHi(to name: String) -> String {
return "Hi \(name) πŸ‘‹"
}
}
// MARK: - Test
print("-------------------- Nasty retain cycle ------------------------\n")
var testRetainCycle: Closureception? = Closureception()
testRetainCycle?.retainCycle()
testRetainCycle = nil
print("πŸ’₯ Should be deallocated!")
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
print("\n-------------------- Time for the right one -----------------\n")
var testRightWay: Closureception? = Closureception()
testRightWay?.rightWay()
testRightWay = nil
print("πŸ’₯ Should be deallocated!")
}
@juliancadi
Copy link
Author

Output

-------------------- Nasty retain cycle ------------------------

Hi Julian πŸ‘‹
πŸ’₯ Should be deallocated!
πŸ‘» Retaining self strongly. And you call yourself iOS developer?...
Hi Alex πŸ‘‹
⚠️ Deallocated

-------------------- Time for the right one -----------------

Hi Julian πŸ‘‹
⚠️ Deallocated
πŸ’₯ Should be deallocated!
☠️ self deallocated ages ago, go away!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment