这个行为能否有人解释一下?

huangapple go评论54阅读模式
英文:

Can somebody please explain this behaviour?

问题

I have translated the code part for you:

让我们假设我有一个类:

class MyClass {
    var fnc: () -> Void
    var int = 1

    init(_ fnc: @escaping () -> Void) {
        self.fnc = fnc
    }
}

然后我执行以下操作:

var foo: MyClass?
foo = MyClass { [weak foo] in
    print("Foo: \(foo?.int)")
}
foo?.fnc()

如果你不使用 "weakify" foo:

var foo: MyClass?
foo = MyClass {
    print("Foo: \(foo?.int)")
}
foo?.fnc()

这种情况下,你将得到期望的结果:Foo: Optional(1)

为什么第一种选项没有捕获 foo? 我确信在调用 foo?.fnc() 时,foo 还没有被销毁。 有人可以解释一下吗?


<details>
<summary>英文:</summary>

Let&#39;s say I have a class:

class MyClass {
var fnc: () -> Void
var int = 1

init(_ fnc: @escaping () -&gt; Void) {
    self.fnc = fnc
}

}


And I do the following:

var foo: MyClass?
foo = MyClass { [weak foo] in
print("Foo: (foo?.int)")
}
foo?.fnc()

I was expecting to get: `Foo: Optional(1)`
Instead I get: `Foo: nil`

If you don&#39;t &quot;weakify&quot; foo:

var foo: MyClass?
foo = MyClass {
print("Foo: (foo?.int)")
}
foo?.fnc()

Indeed I get the expected: `Foo: Optional(1)`

Why doesn&#39;t the first option capture `foo`? 

I am certain `foo` is not deallocated by the time `foo?.fnc()` is called. Can someone please explain?

</details>


# 答案1
**得分**: 2

中文翻译:

在闭包中的方括号 `[...]` 被称为 *捕获列表*。

在第一个示例中,你正在 **捕获** `foo`。

不管之后发生了什么,未初始化的 `foo` 都被传递到了闭包中。

<details>
<summary>英文:</summary>

The square brackets `[...]` in the closure are called *Capture List*

In the first example you are **capturing** `foo`.

Regardless what&#39;s happening later the uninitialized `foo` is passed in the closure.

</details>



huangapple
  • 本文由 发表于 2023年4月6日 22:24:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950654.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定