【问题标题】:Implicit self in @escaping Closures when Reference Cycles are Unlikely to Occur Swift 5.3当引用循环不太可能发生时,@escaping 闭包中的隐式 self Swift 5.3
【发布时间】:2021-01-12 09:04:33
【问题描述】:

使用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 的情况下明确使用。

【问题讨论】:

    标签: ios swift swift5


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-27
      • 1970-01-01
      • 2018-10-11
      • 1970-01-01
      • 2016-12-28
      • 2018-07-17
      相关资源
      最近更新 更多