Swift: Weakly reference function as closure?

211 Views Asked by At

In Swift, I'm currently facing the issue where I need to often wrap functions in closures in order to prevent strong reference cycles when passing on a class's function as a closure parameter. For example, in the scenario below:

class A {
    var foo: () -> Void
}

class B {

    private let a: A

    init() {
        self.a = A()
        a.foo = { [weak self] in self?.foo() } // <- Can this be simplified, while still avoiding strong reference cycles?
    }

    private func foo() {}

}

Having to always type { [weak self] in self?.myFunc() } is not nice, as it opens the door people accidentally introducing memory leaks as they forgot to wrap myFunc in a closure. Is there an easier/more foolproof way that similar behavior can be achieved?

-- Edit

If no easier way exists, I will likely open up a feature request @ Apple for syntax that looks something like:

init() {
    self.a = A()
    a.foo = weak foo
}

where a.foo = weak foo is equivalent to a.foo = { [weak self] in self?.foo() }

Or, when dealing with functions that aren't owned by self:

let b = B()
let a = A()
a.foo = weak b.foo

where a.foo = weak b.foo is equivalent to a.foo = { [weak b] in b?.foo() }

Note: I am not proposing to make closures themselves weakly referencable. I'm simply proposing that weak b.foo is compiled identically to { [weak b] in b?.foo() }

0

There are 0 best solutions below