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

前端 未结 11 1132
梦谈多话
梦谈多话 2020-12-02 07:39

In Objective C you can log the method that is being called using:

NSLog(@\"%s\", __PRETTY_FUNCTION__)

Usually this is used from a logging m

11条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-02 08:33

    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.

提交回复
热议问题