Special literals to get current line number in Swift

January 31, 2019

One interesting feature that Swift has are the idea of special literals. The literals are unique in the way that they are able to obtain information about the code themselves.

Let's take a look at some below:

#file (String) - The name of the file

#line (Int) - The line number

#column (Int) - The column number

#function (String) - The function name

Now you might be wondering, how can this be useful? It can actually be very useful when you're debugging code: let's take a look:

     Outputs the the console a message with information on where the message occured. 
    public static func log(_ message: String,
                         line: Int = #line,
                         file: String = #file,
                         function: String = #function) {

        // Only output code in the DEBUG variant
        #if DEBUG
        print("\(message) called from \(function) \(file):\(line)")