Print calling function

:  ~ 45 sec read

Sometimes you need to find out what called a method. StackOverflow helped me find an answer:

public func printCallingFunction() {
  let syms = Thread.callStackSymbols()
	
  if !syms.isEmpty {
    var sourceString = syms[2] as? String ?? ""
    var separatorSet = CharacterSet(characters: " -[]+?.,")
    var array = sourceString
      .componentsSeparated(by: separatorSet)
      .filter() { !$0.isEmpty }
  }

  // 3 is the class, 4 is the method.
  print("--- \(array[3]) - \(array[4])");
}

There's also this approach, but I don't really like it:

#include <execinfo.h>

void *addr[2];
int nframes = backtrace(addr, sizeof(addr)/sizeof(*addr));
if (nframes > 1) {
  char **syms = backtrace_symbols(addr, nframes);
  NSLog(@"%s: caller: %s", __func__, syms[1]);
  free(syms);
} else {
  NSLog(@"%s: *** Failed to generate backtrace.", __func__);
}