Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

ios - Implicit self in @escaping Closures when Reference Cycles are Unlikely to Occur Swift 5.3

With SE-0269 we won’t need to use explicit anymore in the below case for reference type.

class Test {
    var x = 0
    func execute(_ work: @escaping () -> Void) {
        work()
    }
    func method() {
        execute { [self] in
            x += 1
        }
    }
}

Will this handle [weak self] and [unowned self] or we should explicitly use in the case of weak and unowned for this proposal.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You still need to manually specify weak and unowned captures of self. The only change SE-0269 results in is that you don't need to explicitly write out self. when accessing instance properties/methods when acknowledging that you capture self strongly by using [self].

In case of [weak self] you still need to explicitly write self. in the closure, but when using [unowned self], you can omit self. just as when using [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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...