'Is it possible to inspect the contents of a closure passed as a parameter in Swift?

Working with Xcode 13.2.1 and Swift 5.X

I have a problem with a function that receives a closure as parameter. The code has been working fine and now that I implemented new code calling the same function with a different closure (from a different point), when it is executed, it does not do anything (as if the closure is empty). So I want to debug or inspect what is inside the received closure, but I can't find a way to do it.

I added a simplified example to show what I want to accomplish

var closureA = {
    // code here
    print("Closure A")
}

var closureB = {
    // code here
    print("Closure B")
}

func callWithClosure(closure: (()->Void)? = nil) {
    // code
    print("Closure being passed: \(String(describing: closure))")
    closure.debugDescription
    closure?()
}

callWithClosure(closure: closureA)

The printout is:

Closure being passed: Optional((Function))
Closure A

If I add a breakpoint and try to use po closure I also only see Optional(Function)

Is this a limitation of the LLVM or Xcode?

....e



Solution 1:[1]

So I want to debug or inspect what is inside the received closure, but I can't find a way to do it.

There's no way to print the source code of an arbitrary closure from inside your program.

That said, you can use the debugger to see the code. Set a breakpoint on the closure() call or in the closure you're interested in and debug the program. Execution will stop at the breakpoint, just as with any other code, and you can step through the closure's code. You can also look at the stack trace to see how you reached that point in the code, and you can inspect the calling code to see what closure is being passed in.

If I add a breakpoint and try to use po closure I also only see Optional(Function)

Debugging into a closure works because the debugger knows how to connect the object code to the source code that it was compiled from. But at run time, all the source code has already been compiled -- the contents of the closure itself is object code, not source code that you can inspect. It's a limitation neither of Xcode nor of LLVM -- it's just how software works in a compiled environment.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1