英文:
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's say I have a class:
class MyClass {
var fnc: () -> Void
var int = 1
init(_ fnc: @escaping () -> 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't "weakify" foo:
var foo: MyClass?
foo = MyClass {
print("Foo: (foo?.int)")
}
foo?.fnc()
Indeed I get the expected: `Foo: Optional(1)`
Why doesn'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's happening later the uninitialized `foo` is passed in the closure.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论