在Swift中打印当前文件的类名 [英] Print Class Name of Current File in Swift
问题描述
我正在尝试在Swift中打印当前类的名称。更具体地说,我想实现以下输出:
I'm trying to print the name of the current class in Swift. More specifically, I'd like achieve the following output:
myFunction() in ClassContainingTheFunction
我的功能名称打印正常。这是我最接近打印类名和函数名称:
I have the function name printing fine. This is the closest I've came to printing the class name along with the function name:
println("\(__FUNCTION__) in \(__FILE__)")
打印
myFunction() in path/to/TheFile.swift
和
println("\(__FUNCTION__) in \(object_getClassName(self))")
打印
myFunction() in [mangled class name here]
这两个都接近我想要的,但路径很长,与我在代码中看到的名称相比,错位的类名称可能非常难以理解。
Both of these are close to what I want, but the path is long, and the mangled class name can be very unreadable compared to the name I see in code.
推荐答案
所以您的问题只是显示的字符串的长路径。
我最好的办法是将String缩短为文件名。
So your problem is only the long path for the shown String. My best idea would be to shorten the String to the filename only.
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(...)
将使用真实使用类而不是您使用的名称,如类集群,这是错误的方式。 学习具体的类实现名称会使它更容易。
Since object_getClassNAme(...)
will use the real used class and not the name you used like the the class cluster, it is the wrong way for you. Learning the concrete class implementation names would make it easier though.
而不是测试你使用你获取文件名的方式,比如 __ FILE __
。以下代码生成您要查找的输出:
Instead of test you use your way of getting the filename, like __FILE__
. The following code produces the output you are looking for:
println("\(__FUNCTION__) in \(__FILE__.lastPathComponent.stringByDeletingPathExtension)")
Swift 2.2
在 Swift 2.2 中,旧的标识符已弃用,并替换为 #file
, #line
, #column
, #function
。
Swift 2.2
In Swift 2.2 those old identifiers are deprecated and replaced with #file
, #line
, #column
, and #function
.
print("\(#function) in \(#file.components(separatedBy: "/").last ?? "")")
输出示例:
file81.swift
这篇关于在Swift中打印当前文件的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!