class ClosureGiver {
var closureToGive: () -> Void
init(closureToGive: @escaping () -> Void) {
self.closureToGive = closureToGive
}
func passWithWeakSelf(holder: ClosureHolder) -> Void {
holder.holdingClosure = { [weak self] in
if let self {
self.closureToGive()
} else {
print(" (self is lost)")
}
}
}
func passWithStrongClosure(holder: ClosureHolder) -> Void {
holder.holdingClosure = { [closure = self.closureToGive] in
closure()
}
}
func passPlain(holder: ClosureHolder) -> Void {
holder.holdingClosure = {
self.closureToGive()
}
}
}
class ClosureHolder {
var holdingClosure: () -> Void = {}
}
var closureGiver = ClosureGiver(closureToGive: { print(" initial closure runs") })
var weakSelfClosureHolder = ClosureHolder()
var strongClosureClosureHolder = ClosureHolder()
var plainHolder = ClosureHolder()
closureGiver.passWithWeakSelf(holder: weakSelfClosureHolder)
closureGiver.passWithStrongClosure(holder: strongClosureClosureHolder)
closureGiver.passPlain(holder: plainHolder)
print("before modifying closureToGive")
print("weakSelfClosureHolder.holdingClosure():")
weakSelfClosureHolder.holdingClosure()
print("plainHolder.holdingClosure():")
plainHolder.holdingClosure()
print("strongClosureClosureHolder.holdingClosure():")
strongClosureClosureHolder.holdingClosure()
print("")
closureGiver.closureToGive = { print(" new closure runs") }
print(
#"""
closureGiver.closureToGive = { print(" new closure runs") }
"""#
)
print("after modifying closureToGive")
print("weakSelfClosureHolder.holdingClosure():")
weakSelfClosureHolder.holdingClosure()
print("plainHolder.holdingClosure():")
plainHolder.holdingClosure()
print("strongClosureClosureHolder.holdingClosure():")
strongClosureClosureHolder.holdingClosure()
print("")
closureGiver = ClosureGiver(closureToGive: { print(" new giver's closure runs") })
print(
#"""
closureGiver = ClosureGiver(closureToGive: { print(" new giver's closure runs") })
"""#
)
print("after replacing closureGiver variable")
print("weakSelfClosureHolder.holdingClosure():")
weakSelfClosureHolder.holdingClosure()
print("plainHolder.holdingClosure():")
plainHolder.holdingClosure()
print("strongClosureClosureHolder.holdingClosure():")
strongClosureClosureHolder.holdingClosure()
print("")
plainHolder = ClosureHolder()
plainHolder.holdingClosure = { print(" new plainHolder's closure runs") }
print(
#"""
plainHolder = ClosureHolder()
plainHolder.holdingClosure = { print(" new plainHolder's closure runs") }
"""#
)
print("after replacing plainHolder")
print("weakSelfClosureHolder.holdingClosure():")
weakSelfClosureHolder.holdingClosure()
print("plainHolder.holdingClosure():")
plainHolder.holdingClosure()
print("strongClosureClosureHolder.holdingClosure():")
strongClosureClosureHolder.holdingClosure()
print("")