在Objective-C中,我们可以使用__LINE__
和__PRETTY_FUNCTION__
宏。这些不是用Swift语言公开的。还有另一种方法可以在Swift中获取类似的信息吗?
答案 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")
在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