Swift: Print name of a function stored in a variable

Viewed 410

The following example:

let plus: (Int, Int) -> Int = (+)
print(plus)
debugPrint(plus)

print(UIView.removeFromSuperview)
debugPrint(UIView.removeFromSuperview)

print(UnsafePointer<Int>.distance(to:))
debugPrint(UnsafePointer<Int>.distance(to:))

Prints the useless output:

(Function)
(Function)
(Function)
(Function)
(Function)
(Function)

Is there any way to get function's name in Swift? I mean, not the name of the function which is currently running (#funciton). But the name of a function stored in a variable, or a class function etc. Every language, especially that pretending to be functional, should have such an ability, right?

1 Answers

Swift is a statically dispatched programming language. This results in Swift using memory addresses as much as possible when it needs to call a function. The side effect is the inability to capture the called function name, since in most of the cases it will be a simple memory address.

#function works because this the construct gets replaced at compile time by the caller function (it's not a runtime construct).

If you have the debug symbols available, you could reconstruct the function name from a binary address, however this would require access to the dSYM infrastructure from within your application, which it's unlikely that you'll want to do, since shipping you app along with the debug symbols is an invitation for hackers to reverse engineer with your app.

Dynamically dispatched languages, like Objective-C, keep a reference to the called function (selector), but only if the called function is a method (i.e. a member function). Other languages, like Ruby, JavaScript, are interpreted languages, which makes the function name available at all times.

Related