5

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?

9
  • 1
    Try print(functionName.dynamicType) Commented Aug 29, 2018 at 18:22
  • 3
    I don't know of a single functional language that lets you print the name of closures, lol Commented Aug 29, 2018 at 18:58
  • @Alexander, JS, C#. Commented Aug 29, 2018 at 20:02
  • 1
    @kelin JS, C# are not functional. Swift is not functional Commented Aug 29, 2018 at 21:25
  • 1
    @Kal, it's not an anonymous function. I just assigned an operator to a variable. () required to help compiler to understand it. You can also assign any function like that. Commented Aug 30, 2018 at 9:13

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.