在 Swift 中,如果我有一个捕获 [weak self] 的闭包,在闭包的开头解开可选的 self 是一种好习惯吗?

问题描述:

我在 macOS 应用程序中使用 Swift,Xcode 是 12.5.1.假设我有以下代码:

I am using Swift for a macOS application, Xcode is 12.5.1. Imagine I have the following code:

func performAsyncTask(completion: { [weak self] (error: Error?) in 

     self?.someProperty = 0.0
     self?.someOtherProperty = 0.0
     // Other similar statements follow
})

改成:

func performAsyncTask(completion: { [weak self] (error: Error?) in 
     
     guard let self = self else { return }
     self.someProperty = 0.0
     self.someOtherProperty = 0.0
     // Other similar statements follow
})

我相信第一个实现更好,因为 self 可能在语句之间 变为 nil,因此在开始时展开可能不太干净.我希望专家能给我带来正确的方向.感谢您的关注.

I believe that the first implementation is better because self could become nil between the statements, so unwrapping at the beginning could be less clean. I hope an expert can bring me in the right direction. Thanks for your attention.

我相信第一个实现更好,因为 self 可能在语句之间变为 nil

I believe that the first implementation is better because self could become nil between the statements

这就是为什么 第二 实现实际上更好的原因!如果在第一条语句中 self 不是 nil,那么第一条语句会使得 self couldn't 变成 nil 语句之间.它为块的其余部分保留 self.这就是所谓的弱强之舞".

And that's why the second implementation is in fact better! If self is not nil at the first statement, the first statement makes it so that self couldn't become nil between the statements. It retains self exactly for the remainder of the block. This is called "the weak–strong dance".

guard let self = self else { return }
      //  ^^^^ this self is _strong_, not weak; it retains self