robdashnash robdashnash - 3 months ago 17
Swift Question

Swift: does capturing a function parameter, within a closure, hold it strongly?

Capturing a function parameter within a closure

func someFunction(tableView: UITableView) -> (() -> ()) {

return { [weak self] in

self?.someOtherFunction() {
tableView.performTask()
}

}

}


If so, what is the syntax for ensuring the tableView parameter is weak, in the above example?

Answer

Closure capture parameters strongly by default. In most common cases in closure you accessing to properties declared in self, without capturing other references, so making self weak is enough. In your case you need expand closure capture list and include tableView to it:

func someFunction(tableView: UITableView) -> (() -> ()) {
    return { [weak self, weak tableView] in
        self?.someOtherFunction() {
            tableView?.performTask()
        }
    }
}

You may read more about capture lists in ARC documentation:

You resolve a strong reference cycle between a closure and a class instance by defining a capture list as part of the closure’s definition. A capture list defines the rules to use when capturing one or more reference types within the closure’s body. As with strong reference cycles between two class instances, you declare each captured reference to be a weak or unowned reference rather than a strong reference.