本文介绍了在 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,那么第一条语句会使得 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

这篇关于在 Swift 中,如果我有一个捕获 [weak self] 的闭包,在闭包的开头解开可选的 self 是一种好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 06:56