转义闭包是否捕获强链接?

Escaped closure capture strong links or not?

在我的示例中,我在其他函数中创建了实例。在函数结束时,我希望 instance2 应该是 nil 并且 completionHandlers 数组不应该对 SomeClass2 有强 link 但 completionHandlers 仍然 link on.

看起来 @escaping 闭包在 self 内部创建了强大的 links。

var completionHandlers: [() -> Void] = []

func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
    completionHandlers.append(completionHandler)
}

class SomeClass {
    var x = 10
    func doSomething() {
        let instance2 = SomeClass2()
        instance2.doSomething2()
    }
}

class SomeClass2 {
    var x = 11
    func doSomething2() {
        someFunctionWithEscapingClosure {
            // still exist
            self.x = 77
        }
    }
}

let instance = SomeClass()
instance.doSomething()

completionHandlers.first!()

来自documentation

If you assign a closure to a property of a class instance, and the closure captures that instance by referring to the instance or its members, you will create a strong reference cycle between the closure and the instance. Swift uses capture lists to break these strong reference cycles. For more information, see Strong Reference Cycles for Closures.

你这里没有强引用循环,但有人提到闭包捕获了实例,这就是你的情况。为防止您可以显式地捕获它:

func doSomething2() {
    someFunctionWithEscapingClosure { [weak self] in
        self?.x = 77
    }
}