How to print out the method name and line number in swift

后端 未结 4 1349
礼貌的吻别
礼貌的吻别 2020-12-12 18:26

Here is an example of what I want to do:

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError)
{
            


        
相关标签:
4条回答
  • 2020-12-12 18:31

    You can use #function, #file, #line

    Here is the implementation of log method in swift : https://github.com/InderKumarRathore/SwiftLog

    Below is the snippet

    public func debugLog(object: Any, functionName: String = #function, fileName: String = #file, lineNumber: Int = #line) {
      #if DEBUG
        let className = (fileName as NSString).lastPathComponent
        print("<\(className)> \(functionName) [#\(lineNumber)]| \(object)\n")
      #endif
    }
    
    0 讨论(0)
  • 2020-12-12 18:38
    static func DLog(message: String, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) {
        print("\(file) : \(function) : \(line) : \(column) - \(message)")
    }
    
    0 讨论(0)
  • 2020-12-12 18:44
    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.
    #dsohandle     UnsafeMutablePointer   The dso handle.
    

    Example

    print("Function: \(#function), line: \(#line)") 
    

    With default values in parameters you can also create a function

    public func track(_ message: String, file: String = #file, function: String = #function, line: Int = #line ) { 
        print("\(message) called from \(function) \(file):\(line)") 
    }
    

    which can be used like this

    track("enters app")
    

    In Swift 2.1

     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 more info see the documentation

    0 讨论(0)
  • 2020-12-12 18:53

    For swift 4 and swift 5:

    func printLog(_ message: String, file: String = #file, function: String = #function, line: Int = #line) {
        #if DEVELOPMENT
            let className = file.components(separatedBy: "/").last
            print(" ❌ Error ----> File: \(className ?? ""), Function: \(function), Line: \(line), Message: \(message)")
        #endif
    }
    
    // "❌ Error ----> File: classNameViewController.swift, function: functionName(), Line: 123, Message: messageError"
    
    0 讨论(0)
提交回复
热议问题