我正在尝试在Swift中打印当前类的名称.更具体地说,我想实现以下输出:
myFunction() in ClassContainingTheFunction
Run Code Online (Sandbox Code Playgroud)
我的功能名称打印很好.这是我最接近打印类名和函数名称:
println("\(__FUNCTION__) in \(__FILE__)")
Run Code Online (Sandbox Code Playgroud)
版画
myFunction() in path/to/TheFile.swift
Run Code Online (Sandbox Code Playgroud)
和
println("\(__FUNCTION__) in \(object_getClassName(self))")
Run Code Online (Sandbox Code Playgroud)
版画
myFunction() in [mangled class name here]
Run Code Online (Sandbox Code Playgroud)
这两个都接近我想要的,但路径很长,与我在代码中看到的名称相比,受损的类名称可能非常难以理解.
Bin*_*ian 28
所以你的问题只是所示字符串的长路径.我最好的想法是将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
Run Code Online (Sandbox Code Playgroud)
由于object_getClassNAme(...)将使用真正使用的类而不是您使用的名称,如类集群,这对您来说是错误的.学习具体的类实现名称会使它变得更容易.
而不是测试你使用你的方式获取文件名,如__FILE__.以下代码生成您要查找的输出:
println("\(__FUNCTION__) in \(__FILE__.lastPathComponent.stringByDeletingPathExtension)")
Run Code Online (Sandbox Code Playgroud)
在雨燕2.2的旧标识已被弃用,取而代之的#file,#line,#column,和#function.
print("\(#function) in \(#file.components(separatedBy: "/").last ?? "")")
Run Code Online (Sandbox Code Playgroud)
输出示例:
file81.swift
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9067 次 |
| 最近记录: |