Is there a Swift alternative for NSLog(@"%s", __PRETTY_FUNCTION__)

Swift has #file, #function, #line and #column. From Swift Programming Language:

#file - String - The name of the file in which it appears.

#line - Int - The line number on which it appears.

#column - Int - The column number in which it begins.

#function - String - The name of the declaration in which it appears.


Starting from Swift 2.2 we should use:

  • #file (String) The name of the file in which it appears.
  • #line (Int) The line number on which it appears.
  • #column (Int) The column number in which it begins.
  • #function (String) The name of the declaration in which it appears.

From The Swift Programming Language (Swift 3.1) at page 894.

func specialLiterals() {
    print("#file literal from file: \(#file)")
    print("#function literal from function: \(#function)")
    print("#line: \(#line) -> #column: \(#column)")
}
// Output:
// #file literal from file: My.playground
// #function literal from function: specialLiterals()
// #line: 10 -> #column: 42

Swift 4
Here's my approach:

func pretty_function(_ file: String = #file, function: String = #function, line: Int = #line) {

    let fileString: NSString = NSString(string: file)

    if Thread.isMainThread {
        print("file:\(fileString.lastPathComponent) function:\(function) line:\(line) [M]")
    } else {
        print("file:\(fileString.lastPathComponent) function:\(function) line:\(line) [T]")
    }
}

Make this a global function and just call

pretty_function()

Bonus: You will see the thread is executed on, [T] for a background thread and [M] for the Main thread.

Tags:

Swift