Do capture lists of inner closures need to redeclare `self` as `weak` or `unowned`?

后端 未结 3 886
野性不改
野性不改 2020-12-14 03:20

If I have a closure passed to a function like this:

 someFunctionWithTrailingClosure { [weak self] in
     anotherFunctionWithTrailingClosure { [weak self] i         


        
3条回答
  •  忘掉有多难
    2020-12-14 03:51

    Updated for Swift 4.2:

    public class CaptureListExperiment {
    
        public init() {
    
        }
    
        func someFunctionWithTrailingClosure(closure: @escaping () -> ()) {
            print("starting someFunctionWithTrailingClosure")
    
            DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
                closure()
                print("finishing someFunctionWithTrailingClosure")
            }
        }
    
        func anotherFunctionWithTrailingClosure(closure: @escaping () -> ()) {
            print("starting anotherFunctionWithTrailingClosure")
    
            DispatchQueue.global().asyncAfter(deadline: .now() + 1) {
                closure()
                print("finishing anotherFunctionWithTrailingClosure")
            }
        }
    
        func doSomething() {
            print("doSomething")
        }
    
        public func testCompletionHandlers() {
            someFunctionWithTrailingClosure { [weak self] in
                guard let self = self else { return }
                self.anotherFunctionWithTrailingClosure { // [weak self] in
                    self.doSomething()
                }
            }
        }
    
        // go ahead and add `deinit`, so I can see when this is deallocated
    
        deinit {
            print("deinit")
        }
    }
    

    try it Playgorund:

    func performExperiment() {
    
        let obj = CaptureListExperiment()
    
        obj.testCompletionHandlers()
        Thread.sleep(forTimeInterval: 1.3)
    }
    
    performExperiment()
    

提交回复
热议问题