有没有办法在Swift语言中获取行号和函数名?

时间:2014-06-08 05:47:48

标签: swift

在Objective-C中,我们可以使用__LINE____PRETTY_FUNCTION__宏。这些不是用Swift语言公开的。还有另一种方法可以在Swift中获取类似的信息吗?

3 个答案:

答案 0 :(得分:117)

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.

实施例

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")

有关详细信息,请参阅文档 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Expressions.html#//apple_ref/doc/uid/TP40014097-CH32-ID390

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

实施例

print("Function: \(__FUNCTION__), line: \(__LINE__)") 

答案 1 :(得分:60)

Swift Language Reference defines一些"特殊文字"提供这种行为:

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.

答案 2 :(得分:3)

你可以通过这种方式获得文件名。

let errorLocation =  (#file as NSString).lastPathComponent
print(errorLocation)

let errorLocation = filePath.components(separatedBy: "/").last!
print(errorLocation)

输出

ViewController.swift