About nesting function and implicit capture

I'm using a nesting function C.f.ff, and I'm wondering that is this a implicit strong capture of self.v? how can we declare a weak capture?

import Foundation

class C {
    var v: Int = 0
    func f() {
        func ff() -> Int {
            self.v
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            print(ff()) // Is this a strong implicit capture self.v? how to weak capture?
        }
    }
}
var c: C? = C()
c?.f()
c = nil

// result: 0

Yes, the function implicitly captures the self and in this case, will be released after 1 second after DispatchQueue.main.asyncAfter has completed.

You can make a pure function, for example:

func ff(_ value: Int) -> Int {
    // process data
    return value
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in
    guard let self else { return }

    print(ff(v))
}

or use closure:

let ff: () -> Int? = { [weak self] in
    self?.v
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
    print(ff())
}
1 Like