在Swift中打印当前文件的类名
我正在尝试在Swift中打印当前类的名称。 更具体地说,我想实现以下输出:
myFunction() in ClassContainingTheFunction
我的function名称打印很好。 这是我最接近打印类名和函数名称:
println("\(__FUNCTION__) in \(__FILE__)")
版画
myFunction() in path/to/TheFile.swift
和
println("\(__FUNCTION__) in \(object_getClassName(self))")
版画
myFunction() in [mangled class name here]
这两个都接近我想要的,但路径很长,与我在代码中看到的名称相比,受损的类名称可能非常难以理解。
所以你的问题只是显示字符串的长路径。 我最好的想法是将String缩短为文件名。
var test: String = "/Users/user/Project/classfile.m" test = test.lastPathComponent // here it is only classfile.m test = test.stringByDeletingPathExtension // here it is only classfile
由于object_getClassNAme(...)
将使用实际使用的类而不是您使用的名称(如类集群),因此对您来说这是错误的方法。 学习具体的类实现名称会使它更容易 。
而不是测试你使用你的方式获取文件名,如__FILE__
。 以下代码生成您要查找的输出:
println("\(__FUNCTION__) in \(__FILE__.lastPathComponent.stringByDeletingPathExtension)")
斯威夫特2.2
在Swift 2.2中,旧的标识符已弃用,并替换为#file
, #column
, #column
和#column
。
print("\(#function) in \(#file.components(separatedBy: "/").last ?? "")")
输出示例:
file81.swift
我的简短回答是,
print(" Function name : \(#function), Class Name : \(self.dynamicType), File Path : \(#file)")
我想要一个解决方案,记录出这样一个漂亮的整齐字符串(Swift 3.0) – 类名称 – 函数名称。 例如:
OnboardingGetStartedController – viewDidLoad()
所以我最终得到了一个我在utils类中放入的短函数,如下所示:
class func logCurrentFunc(fileStr: String, funcStr: String) { var fileName = fileStr.components(separatedBy: "/").last ?? "" fileName = fileName.components(separatedBy:".").first ?? "" let printFunc = "\(fileName) - \(funcStr)" print(printFunc) }
我从应用程序的任何地方调用它,如下所示:
Utils.logCurrentFunc(#file, funcStr: #function)
它看起来比其他建议更整洁。
在swift 3中,它现在是#file
和#file
希望有所帮助。
我认为以下是你想要的(在Swift 2.1和更高版本中):
print("\(__FUNCTION__) in \(self.dynamicType)")