I always using [weak self]
in swift closure to prevent reference cycle.
Here is the code below, is it the correct way?
someTask(completion: {[w
You said:
someTask(completion: {[weak self] (result) in
if self == nil {
return
}
//is it safe when reach here?
self!.xxx = yyy
})
No! You have not retained self
, so in theory it might become nil
at any time during the execution of the closure. It probably won't, but "probably" is not good enough. And exclamation marks are always an invitation to crash.
Do the weak-strong dance, and do it correctly:
someTask(completion: {[weak self] (result) in
if let self = self { // or let `self` before Swift 4
// here, self is safe, because you made the reference strong again
self.xxx = yyy
}
})