Is it possible to get the retain count of a Closure in Swift?

427 Views Asked by At

In Swift, Closures are reference types. Which means (I think, please correct me if I'm wrong) that they have a lifetime managed by a retain count. I can get the retain count of an object using CFGetRetainCount, but this doesn't work for Closures because they can't conform to AnyObject (or any protocol for that matter).

Before anyone jumps in and tells me I'm doing the wrong thing by trying to get the retain count of anything manually, I know. It's purely for experimentation to prove to myself that this is how Closure lifetime is managed by the runtime.

1

There are 1 best solutions below

0
Cristik On

You can use CFGetRetainCount if you declare the closure as @convention(block), as this will instruct the compiler to generate an Objective-C block, which is for all intended purposes an object:

let closure: @convention(block) () -> Void = {
    print("test")
}

print(CFGetRetainCount(unsafeBitCast(closure, to: CFTypeRef.self)))