salman siddiqui
salman siddiqui

Reputation: 902

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.

Upvotes: 2

Views: 974

Answers (1)

David Pasztor
David Pasztor

Reputation: 54745

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
}

Upvotes: 6

Related Questions