Is it the right way using `[weak self]` in swift closure?

后端 未结 3 1318
醉梦人生
醉梦人生 2021-01-13 22:48

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         


        
3条回答
  •  情话喂你
    2021-01-13 23:03

    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
        }
    })
    

提交回复
热议问题