4

I can get name of the current function with

__FUNCTION__

But is it possible to get name of another function, for example a function of an object I have in the scope of the called function?

TpoM6oH
  • 8,385
  • 3
  • 40
  • 72
  • 1
    With reflection you can get the type of the function, but i think not its name `func data(number: Int) { return number+2 }` `let x = data` `let mirror = Mirror(reflecting: x)` `print(mirror.subjectType)` It will return Int -> Int – kevinrodriguez-io Mar 03 '16 at 17:29
  • 1
    Does this answer your question? [Get function name in Swift](https://stackoverflow.com/questions/34971522/get-function-name-in-swift) – cbuchart Aug 25 '20 at 08:45
  • @cbuchart no that does not answer the question or am I missing it? That question and its answers seem to only deal with names from inside the function. – gman Oct 13 '22 at 16:13
  • @gman there is certainly such a thing as a function _reference_, and you can store them for calling later. But it's hard to tell whether that would suit you, as there is no use case here. – matt Oct 13 '22 at 16:46
  • @matt, I want to log what function was being used. Example: `sort(fn: (a: Int, b: Int) -> Bool) { print("called with: \(magicFunctionToGetFunctionName(fn))"); return fn(a, b); }`. Of course I wouldn't do this with `sort` but it illustrates the idea. Some languages have this info ([C# for example](https://dotnetfiddle.net/gAGpP2)). Other's don't (C++ IIRC). – gman Oct 14 '22 at 19:23
  • In general, the answer is no at least not easily, but there is an exception. If the function is a method on an Objective-C object (ie. inherits from `NSObject`), you can use the Obj-C runtime calls to the object for its methods/selectors. Or you could swizzle the ones you're interested in. – Chip Jarred Oct 16 '22 at 01:13
  • I think for the general case, what you'd have to do things like make dylib queries, which is only helpful for exported symbols, or load and parse debugger symbols, or somehow instrument the code to provide that information. In that case, you're part way to writing your own debugger/profiler. That's a lot of work for just logging. – Chip Jarred Oct 16 '22 at 01:32
  • This looks like a similar question https://stackoverflow.com/questions/44670876/is-there-a-way-to-get-list-of-variables-and-function-of-a-class – Suyash Medhavi Oct 16 '22 at 05:18

1 Answers1

1

Nope, functions don't store their own names (and closures are anonymous, anyway).

#function (previously __FUNCTION__) is more of a pre-processing-style trick than it is some behaviour that introspects the currect function at runtime.

Alexander
  • 59,041
  • 12
  • 98
  • 151