什么时候在 swift 块中使用 [self] 与 [weak self]?

Vis*_*ukh 4 swift

[self]是我们可以在块中使用的新术语,以避免使用 self 关键字。那么这和 有[weak self]什么不同呢?是否[self]关心保留周期?

我找不到关于此的太多信息,因此将不胜感激任何带有解释的简单示例。

Rob*_*ier 13

[self] indicates that self is intentionally held with a strong reference (and so some syntax is simplified). [weak self] indicates that self is held with a weak reference.

why would I use strong capture [self] inside block as there are chances of memory leak

You would use this when you know there is no reference cycle, or when you wish there to be a temporary reference cycle. Capturing self does not by itself create a cycle. There has to be a cycle. You may know from your code that there isn't. For example, the thing holding the closure may be held by some other object (rather than self). Good composition (and decomposition of complex types into smaller types) can easily lead to this.

Alternately, you may want a temporary cycle. The most common case of this URLSessionTask. The docs are very valuable here (emphasis added):

After you create a task, you start it by calling its resume() method. The session then maintains a strong reference to the task until the request finishes or fails; you don’t need to maintain a reference to the task unless it’s useful for your app’s internal bookkeeping.

Another common example is DispatchQueue, which similarly holds onto a closure until it finishes. At that point, it releases it, killing the cycle and allowing everything to deallocate. This is useful and powerful (and common!), when used with intent. It's a source of bugs when used accidentally. So Swift requires you to state your intentions and tries to make the situation explicit.

当您构建自己的保留完成处理程序的类型时,您也应该强烈考虑这种模式。调用完成处理程序后,将其设置为nil(或{_ in }用于非可选)以释放完成处理程序可能引用的任何内容。

当前情况的一个令人沮丧的影响是开发人员[weak self]不假思索地使用闭包。这与本意相反。看到self应该让开发人员停下来思考参考图。我不确定它是否真的实现了这一点,但作为 Swift 程序员,你应该明白这就是意图。这不仅仅是随机语法。