Special Literals in Swift

Today I learned about special literals in Swift. These literal won't add any functionality benefits to your code, but are excellent while debugging and pinpointing error and bugs. There might be more, but here is the list of literals I came across today.

  • #file

    Outputs the name of the file in which code is being run
  • #function

    Outputs the name of the function where code belongs
  • #line

    Output the line number at which code is being run
  • #column

    Output the column number in which code is being run

There is one more trick where you can even print the name of a calling function. We will see it shortly.

Let's look at the example now,

func callingFunction() {
    calledFunction()
}
    
func calledFunction(callingFunction: String = #function) {
    /*
    Following line prints:
    Calling Function: callingFunction()
    Called function: calledFunction
    Line number: 51
    Column number: 124
    File name: /Users/jayeshkawlibackup/Desktop/git/SwiftSample/JKAdvancedSwift.swift
    */
    print("Calling Function: \(callingFunction)\nCalled function: \(#function)\nLine number: \(#line)\nColumn number: \(#column)\nFile name: \(#file)")
}

Here we have divided code into two functions. First one is a callingFunction and second one is calledFunction.

As you can see we have used special literal to print debug information such as calling and called function, line number and column number etc.

I have used this method in my first ever Swift project successfully. Sometimes code would crash at random location and then it would take me a while to find extra information on calling function, line number and actual function where app crashed. Using this technique, I was quickly able to pinpoint the location of defaulting code. Hope this helps you as well.

If you have any questions about this technique or any other swift questions, do let me know. I would be more than happy to assist you as much as I can (Twitter handle: @jayeshkawli)