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 = NSThread.callStackSymbols()
	
  if !syms.isEmpty {
    var sourceString = syms[2] as? String ?? ""
    var separatorSet = NSCharacterSet(charactersInString: " -[]+?.,")
    var array = sourceString.componentsSeparatedByCharactersInSet(separatorSet).filter() {
      $0 != ""
    }
  }
		
  // Swift appears to be different than Obj-C
  if (array.count < 6) {
    println("--- \(array[3]))");
  }
  else {
    println("--- \(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__);
}