Search code examples
iosswiftnslog

Log line number and method name in Swift


I am converting an Objective C code to Swift. Found out this code :

#define MPLog(fmt, ...) \
    do { \
        if ([MPPush getLoggingPref] && ![MPPush getEnvironmentPref]) { \
            NSLog(fmt, ##__VA_ARGS__); \
        } \
    } while(0)  

I am aware what this code does but I am not able to convert this. I found this great link but this has only Objective C reference.


Solution

  • Swift provides some expressions in order to log, among others line number and method name:

    Literal     Type    Value
    #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.
    

    For example:

    func logFunctionName(string: String = #function) {
        print(string)
    }
    func myFunction() {
        logFunctionName() // Prints "myFunction()".
    }
    

    For more information, check the official documentation