I have two classes, class A and class B. In class A I have declared an optional closure and from class B I am calling that closure. In class B, you can see in callTapA function I am calling the closure with [weak self] to safely release the reference, but in callTapB function I am calling the optional closure and assigning with a function. Both are correct but how is the [weak self] is managed in callTapB ? Is it safe to use closure like this?
class A {
var onTapA: ((_ name: String) -> Void)?
init(onTapA: ((_ name: String) -> Void)? = nil) {
self.onTapA = onTapA
}
}
class B {
var newName:String = ""
let a:A
init(a: A) {
self.a = a
callTapA()
callTapB()
}
func callTapA() {
a.onTapA = { [weak self] name in
guard let self = self else { return }
newName = name
}
}
func callTapB() {
a.onTapA = onTapB
}
func onTapB(name: String) {
newName = name
}
}