Last active
March 10, 2021 23:50
-
-
Save juliancadi/5daf684cbf785191ce1e0c7960996566 to your computer and use it in GitHub Desktop.
Nested closures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output