ios - 当引用循环不太可能发生时,@escaping 闭包中的隐式 self Swift 5.3
问题描述
使用SE-0269,我们将不再需要在以下情况下使用显式引用类型。
class Test {
var x = 0
func execute(_ work: @escaping () -> Void) {
work()
}
func method() {
execute { [self] in
x += 1
}
}
}
这是否会处理 [weak self] 和 [unowned self] 或者我们应该在弱和无主的情况下明确使用此提案。
解决方案
您仍然需要手动指定weak
和unowned
捕获self
. SE-0269 导致的唯一变化是,self.
当您确认您self
使用[self]
.
如果[weak self]
您仍然需要self.
在闭包中显式写入,但是在使用时,您可以像使用时一样[unowned self]
省略。self.
[self]
execute { [weak self] in
x += 1 // Error: Reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit
}
execute { [weak self] in
self?.x += 1 // need to manually specify `self?.`
}
execute { [unowned self] in
x += 1 // compiles fine
}
推荐阅读
- python - QGraphicsView fitInView 具有非常小的视口矩形尺寸
- python - 无效的参数,不是字符串或列,pyspark UDF
- r - 按节点分割图
- flutter - 在不同的构造函数中使用特定类型的联合会破坏缩短的 copyWith
- javascript - 在状态更改时重新渲染功能性 React 组件
- robotframework - 如何使用 DatabaseLibrary 将变量放入选择中?
- javascript - 使不可显示的数据出现在表格的底部
- php - postgres 和 php 可能出现 mdb2 或转义错误
- file - gzip Reader.Close 的意义何在?
- nav - 尝试在不影响页面上所有其他元素的情况下调整图像大小以适应 CSS 中的导航栏