小编典典

如何快速打印出方法名称和行号

swift

这是我想做的一个例子:

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError)
{
    let  nm =  NetworkModel()
    nm.sendlog("file name :AppDelegate , line number : 288", info: " Failed to register: \(error)")
}

在目前的情况下,我做到了硬编码的价值line numberfile name。但是有可能以编程方式选择line number和选择file name


阅读 239

收藏
2020-07-07

共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.
#dsohandle     UnsafeMutablePointer   The dso handle.

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

使用参数中的默认值,您还可以创建一个函数

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

可以这样使用

track("enters app")

在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.

有关更多信息,请参见文档

2020-07-07