首页 > 解决方案 > 当引用循环不太可能发生时,@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] 或者我们应该在弱和无主的情况下明确使用此提案。

标签: iosswiftswift5

解决方案


您仍然需要手动指定weakunowned捕获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
}

推荐阅读